JAVA入门[12]-JavaBean
一.什么是JavaBean
JavaBean是特殊的Java类,使用Java语言书写,并且遵守规范:
- 提供一个默认的无参构造函数。
- 需要被序列化并且实现了Serializable接口。
- 可能有一系列可读写属性。
- 可能有一系列的"getter"或"setter"方法。
二.定义JavaBean
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package com.cathy.domain;
public class Category implements java.io.Serializable{
public Category(){}
private int cateId;
private String cateName;
public int getCateId() {
return cateId;
}
public void setCateId( int cateId) {
this .cateId = cateId;
}
public String getCateName() {
return cateName;
}
public void setCateName(String cateName) {
this .cateName = cateName;
}
} |
三、访问JavaBean
1. <jsp:useBean> 标签可以在JSP中声明一个JavaBean,语法格式如下:
1
|
<jsp:useBean id= "bean 的名字" scope= "bean 的作用域" />
|
其中scope的值可以是page,request,session或application
2.设置和获取JavaBean属性
在 <jsp:useBean> 标签主体中使用 <jsp:getProperty/> 标签来调用 getter 方法获取属性,使用 <jsp:setProperty/> 标签调用 setter 方法设置属性。语法格式:
1
2
3
4
5
6
7
8
|
<jsp:useBean id= "id" class = "bean 类" scope= "bean 作用域" >
<jsp:setProperty name= "bean 的 id" property= "属性名"
value= "value" />
<jsp:getProperty name= "bean 的 id" property= "属性名" />
...........
</jsp:useBean> |
其中name属性指的是Bean的id属性,property属性指的是想要调用的getter或setter方法
四、示例
1.示例:在当前jsp页面设置和获取javabean属性
1
2
3
4
5
6
7
8
9
10
|
<jsp:useBean id= "category" class = "com.cathy.domain.Category" >
<jsp:setProperty name= "category" property= "cateId" value= "2" ></jsp:setProperty>
<jsp:setProperty name= "category" property= "cateName" value= "女装" ></jsp:setProperty>
</jsp:useBean> <div> id:<jsp:getProperty name= "category" property= "cateId" ></jsp:getProperty>
</div> <div> name:<jsp:getProperty name= "category" property= "cateName" ></jsp:getProperty>
</div> |
2.示例:在edit.jsp 页面form表单提交信息,在detail.jsp页面中显示。
edit.jsp
1
2
3
4
5
|
<form action= "/category/detail" method= "post" >
商品id:<input type= "number" name= "cateId" >
商品名称:<input type= "text" name= "cateName" >
<input type= "submit" value= "提交" >
</form> |
detail.jsp
如果表单中的属性名称和JavaBean中属性对应,那么可以简化jsp:setProperty写法,直接property="*"
1
2
3
4
5
6
7
8
9
|
<jsp:useBean id= "category" class = "com.cathy.domain.Category" >
<jsp:setProperty name= "category" property= "*" ></jsp:setProperty>
</jsp:useBean> <table> <tr>
<td>id:</td><td><jsp:getProperty name= "category" property= "cateId" ></jsp:getProperty></td>
</tr>
<tr><td>名称:</td><td><jsp:getProperty name= "category" property= "cateName" ></jsp:getProperty></td></tr>
</table> |
问题:通过表单提交中文数据时遇到乱码问题:
1
|
<%request.setCharacterEncoding( "UTF-8" );%>
|
效果:
3.示例:JavaBean实现访问计数
首先创建计数JavaBean:
1
2
3
4
5
6
7
|
public class Counter {
private int total= 0 ;
public int getTotal() {
return total++;
}
} |
在index.jsp和edit.jsp文件中调用该JavaBean,注意将scope设置为application。
1
2
3
4
|
<jsp:useBean id= "counter" class = "com.cathy.domain.Counter" scope= "application" ></jsp:useBean>
<div> 访问计数:<jsp:getProperty name= "counter" property= "total" ></jsp:getProperty>
</div> |
刷新这两个页面时,都能实现计数器累加。
本文转自 陈敬(Cathy) 博客园博客,原文链接:http://www.cnblogs.com/janes/p/6518322.html,如需转载请自行联系原作者