<!-- useBean里的值只在实例化的时候执行 --> <jsp:useBean id="person" class="com.wzh.test.Person" scope="session"> kk </jsp:useBean> <%=person.getName() %>
生成的servlet文件:
com.wzh.test.Person person = null; synchronized (session) { person = (com.wzh.test.Person) _jspx_page_context.getAttribute("person", javax.servlet.jsp.PageContext.SESSION_SCOPE); if (person == null){ person = new com.wzh.test.Person(); _jspx_page_context.setAttribute("person", person, javax.servlet.jsp.PageContext.SESSION_SCOPE); out.write(" "); out.write(" kk "); out.write(" "); } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title></title> </head> <body> <!-- useBean里的值只在实例化的时候执行 --> <jsp:useBean id="person" class="com.wzh.test.Person" scope="session"> kk </jsp:useBean> <!-- 手动为Bean属性赋值 --> <jsp:setProperty property="name" name="person" value="xx"/> <%=person.getName() %> <!-- 通过参数为Bean属性赋值 --> <jsp:setProperty property="name" name="person" param="name"/> <%=person.getName() %> <!-- http://127.0.0.1:8080/day09/1.jsp?name=123 地址将输出 123 --> <jsp:setProperty property="age" name="person" param="age"/> <!-- 支持8种基本数据类型的转换 (把客户端提交的字符串转换成对应的数据类型)--> <%=person.getAge() %> <jsp:setProperty property="birthday" name="person" param="birthday"/> <%=person.getBirthday() %> -------------------------- <!-- 给所有属性赋值 --> <jsp:setProperty property="*" name="person"/> <%=person.getName() %> <%=person.getAge() %> </br> <jsp:getProperty property="name" name="person"/> </body> </html>
package com.wzh.test; import java.util.Date; public class Person { private String name="aaa"; private int age; private Date birthday; public String getName() { return name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }