简体   繁体   中英

Getting Null value when using 'getProperty' tag in JSP

My jsp code:

    <jsp:useBean id="studentBean" beanName="StudentBean" type="StudentBean" />
     <%
       StudentBean sb=new StudentBean();
       sb.setName("My Name");
       studentBean=sb;
     %>
     <%=studentBean.getName()%>// display: My Name
     <jsp:getProperty name="studentBean" property="name" />// display: null
     <jsp:setProperty name="studentBean" property="name" value="My Name" />
     <jsp:getProperty name="studentBean" property="name" />// display: My Name

This is my StudentBean class:

public class StudentBean{
      private String name;
      public String getName(){
            return name;
      }
      public void setName(String name){
            this.name=name;
      }
}

why i got NULL value when using 'getProperty' tag?

The problem seems to be that once you use the useBean tag to maintain the bean you have to use the setter tag method to set the value and put it back into the respective scope.

Otherwise to get over the problem you will manually need to put it back to the scope:

<jsp:useBean id="studentBean" beanName="com.zakimak.StudentBean" type="com.zakimak.StudentBean"/>
     <%
       StudentBean sb=new StudentBean();
       sb.setName("My Name111");
       studentBean=sb;
       // put the bean back into the page context for page scope as it is the default scope unless specified in tag
       pageContext.setAttribute("studentBean", studentBean);
     %>
     <%=studentBean.getName()%>
     <jsp:getProperty name="studentBean" property="name" />
     <jsp:setProperty name="studentBean" property="name" value="My Namec2" />
     <jsp:getProperty name="studentBean" property="name" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM