JAVA入门[12]-JavaBean

103 阅读2分钟

一.什么是JavaBean

JavaBean是特殊的Java类,使用Java语言书写,并且遵守规范:

  • 提供一个默认的无参构造函数。
  • 需要被序列化并且实现了Serializable接口。
  • 可能有一系列可读写属性。
  • 可能有一系列的"getter"或"setter"方法。

二.定义JavaBean

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,语法格式如下:

<jsp:useBean id="bean 的名字" scope="bean 的作用域" />

其中scope的值可以是page,request,session或application

2.设置和获取JavaBean属性

jsp:useBean 标签主体中使用 jsp:getProperty/ 标签来调用 getter 方法获取属性,使用 jsp:setProperty/ 标签调用 setter 方法设置属性。语法格式:

<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属性

<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

<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="*"

<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>

问题:通过表单提交中文数据时遇到乱码问题:

<%request.setCharacterEncoding("UTF-8");%>

效果:

Image(42)

Image(43)

3.示例:JavaBean实现访问计数

首先创建计数JavaBean:

public class Counter {
    private  int total=0;
 
    public int getTotal() {
        return total++;
    }
}

在index.jsp和edit.jsp文件中调用该JavaBean,注意将scope设置为application。

<jsp:useBean id="counter" class="com.cathy.domain.Counter" scope="application"></jsp:useBean>
<div>
    访问计数:<jsp:getProperty name="counter" property="total"></jsp:getProperty>
</div>

刷新这两个页面时,都能实现计数器累加。