蓝色天空.知识 · 实践 · 创造
我的收藏
JSP 教程目录 32章
JSP / LEARN BY DOING

JSP JavaBean

核对 JavaBean 四项核心规范、可读写/只读/只写属性命名约定、StudentsBean 编译部署,以及 <jsp:useBean>、<jsp:setProperty> 与 <jsp:getProperty> 的作用域和反射机制。

学完这一章,你能够

  • 核对 JavaBean 四项核心规范、可读写/只读/只写属性命名约定、StudentsBean 编译部署,以及 <jsp:useBean>、<jsp:setProperty> 与 <jsp:getProperty> 的作用域和反射机制。

JavaBean 规范特征与属性访问约定

JavaBean 是遵循 JavaBeans API 规范编写的可复用 Java 类,在 JSP 中常用于封装数据模型并与视图解耦。标准 JavaBean 具备四项核心约定:提供 `public` 无参默认构造函数便于容器反射实例化;实现 `java.io.Serializable` 接口以支持会话钝化或网络序列化;将内部状态封装为私有属性;通过规范命名的 `getter` / `setter` 方法对外暴露属性访问。

JavaBean 属性可以是任意基本类型或自定义类,并按提供的访问方法分为可读写(同时具备 `getter` 和 `setter`)、只读(仅提供 `getPropertyName()`,布尔类型亦可为 `isPropertyName()`)或只写(仅提供 `setPropertyName()`)三类,如下表所示。

编写与编译 StudentsBean 示例

以 `StudentsBean` 为例,类定义实现 `java.io.Serializable`,包含 `firstName`、`lastName`、`age` 三个私有字段、无参构造与对应的三对 `getter`/`setter`。注意 Java 要求 `public class StudentsBean` 所在源码文件名必须与类名完全一致为 `StudentsBean.java`(而非 `StudentBean.java`);使用 `javac` 编译后,须按包结构把 `.class` 字节码放入 Web 应用的 `WEB-INF/classes/<包路径>/` 目录供 JSP 容器加载。本站在 OpenJDK 1.8.0_492 下调用标准 `java.beans.Introspector.getBeanInfo()` 实测内省 `StudentsBean`,准确识别 `age`/`firstName`/`lastName` 为可读写、派生 `fullName` 为只读、`auditTag` 为只写,并验证了 `ObjectOutputStream`/`ObjectInputStream` 序列化往返完全一致。

使用 <jsp:useBean>、<jsp:setProperty> 与 <jsp:getProperty>

`<jsp:useBean id="..." scope="..." class="..."/>` 用于在指定作用域(`page`、`request`、`session` 或 `application`,默认 `page`)查找同 `id` 的 Bean 实例;若不存在则自动调用无参构造创建并绑定为同名脚本变量(同一 JSP 中各 `id` 必须唯一)。例如声明 `class="java.util.Date"` 即可直接用 `<%= date %>` 输出当前时间。

对 Bean 属性赋值和取值时,分别使用 `<jsp:setProperty name="..." property="..." value="..."/>` 与 `<jsp:getProperty name="..." property="..."/>`,其中 `name` 对应 `<jsp:useBean>` 的 `id`,`property` 对应属性名(容器会依据 JavaBeans 规范自动反射调用 `setXxx`/`getXxx` 并完成如字符串 `"10"` 到基本类型 `int` 的转换)。本站离线实测基于 `Introspector` 反射完成 `firstName="小强"`、`lastName="王"`、`age="10"` 的写入与读取,准确返回 `age=10`、`fullName="王小强"` 以及跨作用域实例隔离与同作用域复用。

JavaBean 属性访问方法命名约定

方法模式作用与命名示例
getPropertyName()(布尔型可用 isPropertyName())访问器(Getter),用于读取属性值;例如属性名为 myName 时写作 getMyName()。
setPropertyName(Type value)写入器(Setter),用于修改属性值;例如属性名为 myName 时写作 setMyName(...)。

运行 OpenJDK 1.8 JavaBean Introspector 内省、序列化与 useBean/setProperty 反射实测

含完整源码 · 246 行
展开查看收起
java
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class ExploreJavabean {

    public static class StudentsBean implements Serializable {
        private static final long serialVersionUID = 1L;
        private String firstName = null;
        private String lastName = null;
        private int age = 0;
        private String auditTag = "";

        public StudentsBean() {
        }

        public String getFirstName() { return firstName; }
        public String getLastName() { return lastName; }
        public int getAge() { return age; }

        public void setFirstName(String firstName) { this.firstName = firstName; }
        public void setLastName(String lastName) { this.lastName = lastName; }
        public void setAge(int age) { this.age = age; }

        // Read-only derived property (getter only)
        public String getFullName() {
            return (lastName == null ? "" : lastName) + (firstName == null ? "" : firstName);
        }

        // Write-only property (setter only)
        public void setAuditTag(String tag) { this.auditTag = tag; }

        String peekAuditTag() { return auditTag; }
    }

    static class JspBeanRegistry {
        private final Map<String, Map<String, Object>> scopes = new LinkedHashMap<>();

        JspBeanRegistry() {
            scopes.put("page", new LinkedHashMap<>());
            scopes.put("request", new LinkedHashMap<>());
            scopes.put("session", new LinkedHashMap<>());
            scopes.put("application", new LinkedHashMap<>());
        }

        Object useBean(String id, String scope, Class<?> cls) throws Exception {
            Map<String, Object> bag = scopes.get(scope);
            if (!bag.containsKey(id)) {
                bag.put(id, cls.getDeclaredConstructor().newInstance());
            }
            return bag.get(id);
        }

        void setProperty(Object bean, String property, String rawValue) throws Exception {
            BeanInfo info = Introspector.getBeanInfo(bean.getClass(), Object.class);
            for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
                if (pd.getName().equals(property) && pd.getWriteMethod() != null) {
                    Method setter = pd.getWriteMethod();
                    Class<?> paramType = setter.getParameterTypes()[0];
                    Object converted = (paramType == int.class || paramType == Integer.class)
                        ? Integer.parseInt(rawValue)
                        : rawValue;
                    setter.invoke(bean, converted);
                    return;
                }
            }
            throw new IllegalArgumentException("No writable property: " + property);
        }

        Object getProperty(Object bean, String property) throws Exception {
            BeanInfo info = Introspector.getBeanInfo(bean.getClass(), Object.class);
            for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
                if (pd.getName().equals(property) && pd.getReadMethod() != null) {
                    return pd.getReadMethod().invoke(bean);
                }
            }
            throw new IllegalArgumentException("No readable property: " + property);
        }
    }

    public static void main(String[] args) throws Exception {
        List<Map<String, Object>> cases = new ArrayList<>();

        // Case 1: Real java.beans.Introspector property inspection (rw / ro / wo) & Serializable round-trip
        BeanInfo beanInfo = Introspector.getBeanInfo(StudentsBean.class, Object.class);
        Map<String, String> propModes = new LinkedHashMap<>();
        for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
            boolean r = pd.getReadMethod() != null;
            boolean w = pd.getWriteMethod() != null;
            String mode = (r && w) ? "rw" : (r ? "ro" : "wo");
            propModes.put(pd.getName(), mode);
        }

        StudentsBean original = new StudentsBean();
        original.setFirstName("小强");
        original.setLastName("王");
        original.setAge(10);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(original);
        }
        StudentsBean restored;
        try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) {
            restored = (StudentsBean) ois.readObject();
        }

        Map<String, Object> introExp = new LinkedHashMap<>();
        introExp.put("age_mode", "rw");
        introExp.put("firstName_mode", "rw");
        introExp.put("lastName_mode", "rw");
        introExp.put("fullName_mode", "ro");
        introExp.put("auditTag_mode", "wo");
        introExp.put("serializable_roundtrip_match", true);

        Map<String, Object> introAct = new LinkedHashMap<>();
        introAct.put("age_mode", propModes.get("age"));
        introAct.put("firstName_mode", propModes.get("firstName"));
        introAct.put("lastName_mode", propModes.get("lastName"));
        introAct.put("fullName_mode", propModes.get("fullName"));
        introAct.put("auditTag_mode", propModes.get("auditTag"));
        introAct.put("serializable_roundtrip_match",
            "小强".equals(restored.getFirstName())
                && "王".equals(restored.getLastName())
                && restored.getAge() == 10);
        addCase(cases, "javabean_introspector_and_serialization",
            "使用 java.beans.Introspector 内省验证可读写/只读/只写属性,并完成 Serializable 序列化往返。",
            introExp, introAct);

        // Case 2: <jsp:useBean> scope lookup & instantiation (java.util.Date & StudentsBean)
        JspBeanRegistry reg = new JspBeanRegistry();
        Date date1 = (Date) reg.useBean("date", "page", Date.class);
        Date date2 = (Date) reg.useBean("date", "page", Date.class);
        StudentsBean sPage = (StudentsBean) reg.useBean("students", "page", StudentsBean.class);
        StudentsBean sSession = (StudentsBean) reg.useBean("students", "session", StudentsBean.class);

        Map<String, Object> scopeExp = new LinkedHashMap<>();
        scopeExp.put("date_is_util_date", true);
        scopeExp.put("same_scope_reuses_instance", true);
        scopeExp.put("different_scopes_isolated", true);

        Map<String, Object> scopeAct = new LinkedHashMap<>();
        scopeAct.put("date_is_util_date", date1 != null && date1.getTime() > 0L);
        scopeAct.put("same_scope_reuses_instance", date1 == date2);
        scopeAct.put("different_scopes_isolated", sPage != sSession);
        addCase(cases, "jsp_usebean_scope_lifecycle",
            "验证 jsp:useBean 按 page/request/session/application 作用域复用同 id 实例并隔离跨作用域实例。",
            scopeExp, scopeAct);

        // Case 3: <jsp:setProperty> & <jsp:getProperty> with String->int type conversion
        reg.setProperty(sPage, "firstName", "小强");
        reg.setProperty(sPage, "lastName", "王");
        reg.setProperty(sPage, "age", "10");
        reg.setProperty(sPage, "auditTag", "verified");

        Map<String, Object> propExp = new LinkedHashMap<>();
        propExp.put("firstName", "小强");
        propExp.put("lastName", "王");
        propExp.put("age", 10);
        propExp.put("fullName", "王小强");
        propExp.put("auditTag_written", "verified");

        Map<String, Object> propAct = new LinkedHashMap<>();
        propAct.put("firstName", reg.getProperty(sPage, "firstName"));
        propAct.put("lastName", reg.getProperty(sPage, "lastName"));
        propAct.put("age", reg.getProperty(sPage, "age"));
        propAct.put("fullName", reg.getProperty(sPage, "fullName"));
        propAct.put("auditTag_written", sPage.peekAuditTag());
        addCase(cases, "jsp_set_and_get_property_reflection",
            "通过 Introspector 反射执行 setProperty(含字符串 \"10\" 自动转 int)与 getProperty 读取全部属性。",
            propExp, propAct);

        Map<String, Object> root = new LinkedHashMap<>();
        root.put("version", "OpenJDK " + System.getProperty("java.version"));
        root.put("cases", cases);
        System.out.println(toJson(root));
    }

    private static void addCase(List<Map<String, Object>> cases, String name, String summary, Object expected, Object actual) {
        Map<String, Object> c = new LinkedHashMap<>();
        c.put("name", name);
        c.put("summary", summary);
        c.put("expected", expected);
        c.put("actual", actual);
        c.put("passed", Objects.equals(expected, actual));
        cases.add(c);
    }

    private static String toJson(Object obj) {
        if (obj == null) return "null";
        if (obj instanceof Boolean || obj instanceof Number) return obj.toString();
        if (obj instanceof String) return escapeString((String) obj);
        if (obj instanceof List<?>) {
            StringBuilder sb = new StringBuilder("[");
            List<?> list = (List<?>) obj;
            for (int i = 0; i < list.size(); i++) {
                if (i > 0) sb.append(",");
                sb.append(toJson(list.get(i)));
            }
            return sb.append("]").toString();
        }
        if (obj instanceof Map<?, ?>) {
            StringBuilder sb = new StringBuilder("{");
            boolean first = true;
            for (Map.Entry<?, ?> e : ((Map<?, ?>) obj).entrySet()) {
                if (!first) sb.append(",");
                first = false;
                sb.append(escapeString(String.valueOf(e.getKey()))).append(":").append(toJson(e.getValue()));
            }
            return sb.append("}").toString();
        }
        return escapeString(String.valueOf(obj));
    }

    private static String escapeString(String s) {
        StringBuilder sb = new StringBuilder("\"");
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            switch (ch) {
                case '"': sb.append("\\\""); break;
                case '\\': sb.append("\\\\"); break;
                case '\b': sb.append("\\b"); break;
                case '\f': sb.append("\\f"); break;
                case '\n': sb.append("\\n"); break;
                case '\r': sb.append("\\r"); break;
                case '\t': sb.append("\\t"); break;
                default:
                    if (ch < 0x20) sb.append(String.format("\\u%04x", (int) ch));
                    else sb.append(ch);
            }
        }
        return sb.append("\"").toString();
    }
}
验证 Introspector 识别 rw/ro/wo 属性与 Serializable 往返、四级作用域实例复用与隔离,以及 setProperty 字符串转 int 反射调用。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1388.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:JSP

课程关联工程包(登记关联32章) · 含当前章节或实例 · mbskycom202612a1388.zip

下载课程关联工程包:JSP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1407.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

JSP 容器转译生成的 Servlet 在目标作用域未找到已有实例时,需要通过反射调用该类的公开无参构造函数实例化对象;若只定义了带参构造函数而未显式声明无参构造,容器实例化会失败并抛出异常。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习