在JSP中使用'getProperty'标记时获取Null值

时间:2015-01-20 13:55:22

标签: java jsp javabeans

我的jsp代码:

    <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

这是我的StudentBean类:

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

为什么我在使用'getProperty'标签时得到 NULL 值?

1 个答案:

答案 0 :(得分:0)

问题似乎是,一旦使用 useBean 标记来维护bean,就必须使用setter标记方法来设置值并将其放回相应的范围。

否则,为了解决问题,您需要手动将其放回范围:

<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" />