JSP JavaBean

JavaBean 规范、useBean / setProperty / getProperty、作用域与最佳实践。

Beginner
Key PointsJavaBean 就是无参构造 + 私有字段 + getter/setter 的普通类;JSP 用 jsp:useBean 把它放进某个作用域。

JavaBean 规范

  1. 公开的无参构造函数 —— 容器要能 newInstance()
  2. 私有字段 + 公开 getter/setter —— 属性名由方法名推出
  3. 可序列化 —— 实现 Serializable,便于会话持久化
Java
package com.example;

import java.io.Serializable;

public class User implements Serializable {
    private int id;
    private String name;
    private String email;

    public User() { }

    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }

    // 布尔属性的 getter 可以叫 isXxx
    public boolean isActive() { return id > 0; }
}

The property name comes from getName/setName: strip the prefix and lowercase the first letter. A field named userName with getName exposes the property name — EL follows the methods, not the field.

在 JSP 里用

JSP
<%@ page contentType="text/html;charset=UTF-8" %>

<jsp:useBean id="user" class="com.example.User" scope="request"/>

<%-- 手动赋值 --%>
<jsp:setProperty name="user" property="name" value="张三"/>

<%-- 自动绑定同名请求参数 --%>
<jsp:setProperty name="user" property="*"/>

<p>ID:<jsp:getProperty name="user" property="id"/></p>
<p>姓名:<jsp:getProperty name="user" property="name"/></p>

<%-- 用 EL 更简洁 --%>
<p>邮箱:${user.email}</p>
Output
ID:0
姓名:张三
邮箱:

<jsp:useBean> means "find, create only if absent": an existing object in that scope is reused. That makes it safe to place anywhere on the page.

四种作用域

scopeLifetimeTypical use
page当前页面临时对象
request当前请求Controller 传给 View 的数据
session当前会话登录用户、购物车
application整个应用全局配置、缓存

为什么现在少用 useBean

JSP
<%-- useBean 写法:三行标签,属性名靠字符串,改错不报错 --%>
<jsp:useBean id="user" class="com.example.User" scope="request"/>
<jsp:setProperty name="user" property="*"/>
<p><jsp:getProperty name="user" property="name"/></p>

<%-- Controller + EL 写法:数据由 Servlet 准备,页面只读 --%>
<p>${user.name}</p>

property="*" is hard to debug: a typo or type mismatch raises nothing, the property is just empty. Modern practice constructs and populates the bean explicitly in the servlet and lets the page read with EL — a breakpoint then tells the whole story.

Never do heavy work in a getter — EL calls it on every evaluation, so ${user.total} appearing a dozen times means a dozen queries. Compute once in the controller and store the result.

Friends & Partners