jsp:setProperty

类声明:

package test;

public class Student {
    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
jsp代码:    

<jsp:useBean id="student" scope="session" class="test.Student"></jsp:useBean>
<jsp:setProperty property="age" name="student"  value="12"/>
 <jsp:setProperty property="age" name="student"  param="12"/>  此处12只是一个参数名字
 <jsp:getProperty property="age" name="student"/>


=》12

源码如下:

 

      test.Student student = null;
      synchronized (session) {
        student = (test.Student) _jspx_page_context.getAttribute("student", PageContext.SESSION_SCOPE);
        if (student == null){
          student = new test.Student();
          _jspx_page_context.setAttribute("student", student, PageContext.SESSION_SCOPE);
        }
      }
      out.write("\r\n");
      out.write("  \t");
      org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(_jspx_page_context.findAttribute("student"), "age", "12", null, null, false);
      out.write("\r\n");
      out.write("  \t");
      org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(_jspx_page_context.findAttribute("student"), "age", request.getParameter("12"), request, "12", false);
      out.write("\r\n");
      out.write("  \t");
      out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString((((test.Student)_jspx_page_context.findAttribute("student")).getAge())));

 

解释:

1.

<jsp:useBean id="student" scope="request" class="test.Student"></jsp:useBean>

<jsp:setProperty property="age" name="student"  value="12"/>必须和<jsp:useBean配套使用

2.在useBean中声明要放在哪个useBean范围内:page,request,session,application,然后指定id也就是属性名和class也就是属性类型。

3.利用setProperty往useBean声明的变量中放置值,property为属性的变量名,name为useBean中声明的id名这两者必须相同,因为是将值设置到id指定的属性中去,value直接设置属性值,param则是接受传递过来的参数值设置到属性中,如request.getParameter。

param例子:

test2.jsp:

<jsp:forward page="test3.jsp">
<jsp:param value="10" name="age"/>
</jsp:forward>

test3.jsp:

<jsp:useBean id="student" scope="request" class="test.Student"></jsp:useBean>
<jsp:setProperty property="age" name="student" param="age"/>
<jsp:getProperty property="age" name="student"/>


结果为:10


4.通过getProperty从id中取直,property指定属性名,那么指定从哪个id中取值。

注意:修改scope范围生成的servlet中的源代码只有以下部分发生改变

  synchronized (session) {
        student = (test.Student) _jspx_page_context.getAttribute("student", PageContext.SESSION_SCOPE);
        if (student == null){
          student = new test.Student();
          _jspx_page_context.setAttribute("student", student, PageContext.SESSION_SCOPE);
        }
      }

此代码先判断在session中是否存在student对象不存在创建一个放入session中,如果存在则不创建。之后设置值时就是往该对象中放置。



 

posted @ 2013-08-30 18:58  pangbangb  阅读(805)  评论(0编辑  收藏  举报