3.6.2 setProperty和getProperty
setProperty
动作可对一个Java
对象的属性设置属性值,而getProperty
动作则会输出Java
对象的一个属性的属性值。
实例
Person
类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| package app03a; public class Person { private String id; private String firstName; private String lastName; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
|
getSetPropertyTest.jsp
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <title>getProperty and setProperty</title> </head> <body> <%-- 创建一个app03a.Person类的对象,并把它保存在脚本变量employee中 --%> <jsp:useBean id="employee" class="app03a.Person" /> <%-- 设置id为employee这个脚本变量所对应的对象的firstName成员变量的值为Blue --%> <jsp:setProperty name="employee" property="firstName" value="Blue" /> First Name: <%-- 取出id为employee这个脚本变量所对应的对象的firstName成员变量的值 --%> <jsp:getProperty name="employee" property="firstName" /> </body> </html>
|
访问这个JSP,显示效果如下:
打开JSP页面转换成的getSetPropertyTest_jsp.java
这个Servlet中的_jspService
方法.可以看到上面的JSP页面被转换成如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| out.write("<!DOCTYPE html>\r\n"); out.write("<html>\r\n"); out.write("<head>\r\n"); out.write("<title>getProperty and setProperty</title>\r\n"); out.write("</head>\r\n"); out.write("<body>\r\n"); out.write("\r\n"); out.write("\t"); app03a.Person employee = null; employee = (app03a.Person) _jspx_page_context.getAttribute( "employee", javax.servlet.jsp.PageContext.PAGE_SCOPE); if (employee == null){ employee = new app03a.Person(); _jspx_page_context.setAttribute( "employee", employee, javax.servlet.jsp.PageContext.PAGE_SCOPE); } out.write('\r'); out.write('\n'); out.write(' '); out.write('\r'); out.write('\n'); out.write(' '); org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper( _jspx_page_context.findAttribute("employee"), "firstName", "Blue", null, null, false); out.write("\r\n"); out.write("\tFirst Name:\r\n"); out.write("\t"); out.write('\r'); out.write('\n'); out.write(' '); out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString( (((app03a.Person)_jspx_page_context.findAttribute("employee")).getFirstName())) ); out.write("\r\n"); out.write("</body>\r\n"); out.write("</html>");
|
原文链接: 3.6.2 setProperty和getProperty