在JSP中,有几个专门针对JavaBean标签,下面来罗列一下他们的用处,其实很简单,首先是创建一个Bean
package com.bird.domain; import java.util.Date; public class Person { private String name = "小白"; private int age; private Date birthday; public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
首先是JSP的useBann标签,实例代码如下
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>JSP:UseBean标签的使用</title> </head> <body> <!-- userbean标签只在实例化Bean的时候才执行 --> <jsp:useBean id="person" class="com.bird.domain.Person" scope="page"></jsp:useBean> <%=person.getName() %> </body> </html>
其中,scope作用域为本页面,可以设置session和那几个域,
然后就是jsp:setproperity的标签了
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>jsp:setProprity标签</title> </head> <body> <jsp:useBean id="person" class="com.bird.domain.Person" scope="page"></jsp:useBean> <%-- <!-- 手工为Bean赋值 --> <jsp:setProperty property="name" name="person" value="bai"/> <%=person.getName() %> --%> <!-- 用请求参数为bean进行赋值 --> <jsp:setProperty name="person" property="name" param="name"/> <jsp:setProperty name="person" property="age" param="age"/><!-- 只支持8种常量的互相转换 --> <!-- 对于其他的非8种类型转换,可以使用表达式 --> <%-- <jsp:setProperty name="person" property="birthday" value="<%=new Date() %>"/> <%=person.getName() %><br/> <%=person.getAge() %> --%> </body> </html>
其中,name为JavaBean的名称,properity为需要设置的名称,param为客户端带过来的数据