JSP与JavaBean完美结合开发动态网站的实战技巧与应用案例解析

引言:JSP与JavaBean的黄金组合
在Java Web开发的历史长河中,JSP(JavaServer Pages)与JavaBean的结合堪称经典架构模式。这种MVC(Model-View-Controller)设计模式的早期实现,至今仍在许多企业级应用中发挥着重要作用。本文将深入探讨这一技术组合的实战技巧,并通过完整的应用案例展示其在动态网站开发中的强大威力。
为什么选择JSP+JavaBean架构?
JSP作为视图层技术,擅长处理页面展示和用户交互;JavaBean作为模型层,负责封装业务逻辑和数据。这种分离关注点的设计带来了以下优势:
代码复用性高
:JavaBean可以在多个JSP页面中重复使用
维护成本低
:业务逻辑与页面展示分离,便于团队协作开发
开发效率高
:JSP的内置对象和标签库简化了动态内容生成
可扩展性强
:便于后续引入Servlet控制器,平滑过渡到完整MVC架构
JavaBean设计规范与最佳实践
标准JavaBean规范
一个合格的JavaBean必须遵循以下规范:
package com.example.model;

import java.io.Serializable;

/**
* 用户实体类 – 标准JavaBean示例
* 必须实现Serializable接口以便在网络间传输
*/
public class User implements Serializable {
private static final long serialVersionUID = 1L;

// 私有属性
private int id;
private String username;
private String password;
private String email;
private java.util.Date createTime;

// 无参构造函数(必须)
public User() {
super();
}

// 带参构造函数(可选但推荐)
public User(int id, String username, String password, String email) {
this.id = id;
this.username = username;
this.password = password;
this.email = email;
this.createTime = new java.util.Date();
}

// Getter和Setter方法(必须)
public int getId() {
return id;
}

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

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getEmail() {
return email;
}

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

public java.util.Date getCreateTime() {
return createTime;
}

public void setCreateTime(java.util.Date createTime) {
this.createTime = createTime;
}

// 业务方法示例
public boolean validate() {
return username != null && !username.trim().isEmpty()
&& password != null && password.length() >= 6;
}

// 重写toString便于调试
@Override
public String toString() {
return “User [id=” + id + “, username=” + username + “, email=” + email + “]”;
}
}
高级JavaBean设计技巧
1. 使用Builder模式构建复杂对象
public class Product implements Serializable {
private static final long serialVersionUID = 1L;

private final String name;
private final double price;
private final String category;
private final int stock;
private final String description;

// 私有构造函数
private Product(Builder builder) {
this.name = builder.name;
this.price = builder.price;
this.category = builder.category;
this.stock = builder.stock;
this.description = builder.description;
}

// 静态内部Builder类
public static class Builder {
private String name;
private double price;
private String category;
private int stock;
private String description;

public Builder name(String name) {
this.name = name;
return this;
}

public Builder price(double price) {
this.price = price;
return this;
}

public Builder category(String category) {
this.category = category;
return this;
}

public Builder stock(int stock) {
this.stock = stock;
return this;
}

public Builder description(String description) {
this.description = description;
return this;
}

public Product build() {
return new Product(this);
}
}

// Getter方法(无Setter,保证不可变性)
public String getName() { return name; }
public double getPrice() { return price; }
public String getCategory() { return category; }
public int getStock() { return stock; }
public String getDescription() { return description; }
}
2. 使用Apache Commons BeanUtils简化操作
// Maven依赖
//
// commons-beanutils
// commons-beanutils
// 1.9.4
//

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

public class BeanUtilsDemo {
public static void main(String[] args) throws Exception {
User user = new User();

// 动态设置属性
BeanUtils.setProperty(user, “username”, “john_doe”);
BeanUtils.setProperty(user, “email”, “john@example.com”);

// 动态获取属性
String username = BeanUtils.getProperty(user, “username”);
System.out.println(“Username: ” + username);

// 复制属性
User user2 = new User();
BeanUtils.copyProperties(user2, user);

// 获取属性描述
PropertyUtils.getPropertyDescriptor(user, “username”);
}
}
JSP核心语法与JavaBean集成
JSP动作标签详解
1.

– 实例化JavaBean
<%-- 基本用法 --%>

<%-- 带scope的用法 --%>

<%-- 带初始化参数的用法 --%>




2.

– 设置属性值
<%-- 从请求参数设置属性 --%>

<%-- 指定参数名设置 --%>

<%-- 直接设置值 --%>

3.

– 获取属性值

用户名:

邮箱:

JSP表达式语言(EL)与JavaBean
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%-- 使用EL访问JavaBean属性 --%>





用户信息

用户信息展示

属性名 值
用户名 ${currentUser.username}
邮箱 ${currentUser.email}
创建时间 ${currentUser.createTime}

<%-- 使用JSTL条件判断 --%>

欢迎,${currentUser.username}!




JSTL标签库与JavaBean结合
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<%-- 准备产品列表数据 --%>




产品列表

产品目录

<%-- 使用c:forEach遍历JavaBean集合 --%>


产品名称 价格 分类 库存
${product.name} <%-- 使用fmt格式化数字 --%>
${product.category}
0}”>紧张
缺货

<%-- 空数据处理 --%>

暂无产品数据




实战案例:用户注册登录系统
1. 项目结构
/user-app
├── src/
│ └── com/
│ └── example/
│ ├── model/
│ │ ├── User.java
│ │ └── UserSession.java
│ ├── service/
│ │ ├── UserService.java
│ │ └── DatabaseConnection.java
│ └── dao/
│ ├── UserDAO.java
│ └── UserDAOImpl.java
├── web/
│ ├── register.jsp
│ ├── login.jsp
│ ├── welcome.jsp
│ ├── logout.jsp
│ └── WEB-INF/
│ ├── web.xml
│ └── lib/
│ └── (相关JAR包)
└── database/
└── init.sql
2. 核心JavaBean实现
User.java
package com.example.model;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {
private static final long serialVersionUID = 1L;

private int id;
private String username;
private String password;
private String email;
private Date createTime;
private boolean active;

public User() {}

public User(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
this.createTime = new Date();
this.active = true;
}

// Getters and Setters
public int getId() { return id; }
public void setId(int id) { this.id = id; }

public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }

public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }

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

public Date getCreateTime() { return createTime; }
public void setCreateTime(Date createTime) { this.createTime = createTime; }

public boolean isActive() { return active; }
public void setActive(boolean active) { this.active = active; }

// 业务验证方法
public boolean isValid() {
return username != null && username.length() >= 3 &&
password != null && password.length() >= 6 &&
email != null && email.contains(“@”);
}

// 密码加密(实际应用中应使用更安全的加密算法)
public void encryptPassword() {
if (password != null) {
// 简单示例,实际应使用BCrypt等
this.password = “ENC_” + password.hashCode();
}
}

// 密码验证
public boolean checkPassword(String inputPassword) {
if (password == null || inputPassword == null) return false;
return (“ENC_” + inputPassword.hashCode()).equals(password);
}
}
UserSession.java (会话管理Bean)
package com.example.model;

import java.io.Serializable;

public class UserSession implements Serializable {
private static final long serialVersionUID = 1L;

private User user;
private long loginTime;
private String sessionId;

public UserSession() {}

public UserSession(User user, String sessionId) {
this.user = user;
this.sessionId = sessionId;
this.loginTime = System.currentTimeMillis();
}

// Getters and Setters
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }

public long getLoginTime() { return loginTime; }
public void setLoginTime(long loginTime) { this.loginTime = loginTime; }

public String getSessionId() { return sessionId; }
public void setSessionId(String sessionId) { this.sessionId = sessionId; }

// 获取登录时长(分钟)
public long getLoginDurationMinutes() {
return (System.currentTimeMillis() – loginTime) / (1000 * 60);
}

// 会话是否有效(例如30分钟无操作则失效)
public boolean isValid() {
return getLoginDurationMinutes() < 30; } } UserService.java (业务逻辑Bean) package com.example.service; import com.example.model.User; import com.example.dao.UserDAO; import com.example.dao.UserDAOImpl; public class UserService { private UserDAO userDAO; public UserService() { this.userDAO = new UserDAOImpl(); } // 用户注册 public String registerUser(User user) { if (user == null || !user.isValid()) { return "用户数据无效"; } // 检查用户名是否已存在 if (userDAO.usernameExists(user.getUsername())) { return "用户名已存在"; } // 加密密码 user.encryptPassword(); // 保存用户 if (userDAO.save(user)) { return "success"; } else { return "注册失败,请稍后重试"; } } // 用户登录 public User loginUser(String username, String password) { if (username == null || password == null) { return null; } User user = userDAO.findByUsername(username); if (user != null && user.checkPassword(password)) { return user; } return null; } // 检查用户名是否存在 public boolean checkUsername(String username) { return userDAO.usernameExists(username); } // 获取用户信息 public User getUserInfo(int userId) { return userDAO.findById(userId); } } DatabaseConnection.java (数据库连接Bean) package com.example.service; import java.sql.*; public class DatabaseConnection { private static final String URL = "jdbc:mysql://localhost:3306/userdb?useSSL=false&serverTimezone=UTC"; private static final String USER = "root"; private static final String PASSWORD = "password"; static { try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException { return DriverManager.getConnection(URL, USER, PASSWORD); } public static void close(Connection conn, Statement stmt, ResultSet rs) { try { if (rs != null) rs.close(); } catch (SQLException e) {} try { if (stmt != null) stmt.close(); } catch (SQLException e) {} try { if (conn != null) conn.close(); } catch (SQLException e) {} } } UserDAOImpl.java (数据访问Bean) package com.example.dao; import com.example.model.User; import com.example.service.DatabaseConnection; import java.sql.*; import java.util.ArrayList; import java.util.List; public class UserDAOImpl implements UserDAO { @Override public boolean save(User user) { String sql = "INSERT INTO users (username, password, email, create_time, active) VALUES (?, ?, ?, ?, ?)"; Connection conn = null; PreparedStatement pstmt = null; try { conn = DatabaseConnection.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.getUsername()); pstmt.setString(2, user.getPassword()); pstmt.setString(3, user.getEmail()); pstmt.setTimestamp(4, new Timestamp(user.getCreateTime().getTime())); pstmt.setBoolean(5, user.isActive()); return pstmt.executeUpdate() > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
DatabaseConnection.close(conn, pstmt, null);
}
}

@Override
public User findByUsername(String username) {
String sql = “SELECT * FROM users WHERE username = ?”;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;

try {
conn = DatabaseConnection.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
rs = pstmt.executeQuery();

if (rs.next()) {
User user = new User();
user.setId(rs.getInt(“id”));
user.setUsername(rs.getString(“username”));
user.setPassword(rs.getString(“password”));
user.setEmail(rs.getString(“email”));
user.setCreateTime(rs.getTimestamp(“create_time”));
user.setActive(rs.getBoolean(“active”));
return user;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DatabaseConnection.close(conn, pstmt, rs);
}
return null;
}

@Override
public boolean usernameExists(String username) {
String sql = “SELECT COUNT(*) FROM users WHERE username = ?”;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;

try {
conn = DatabaseConnection.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
rs = pstmt.executeQuery();

if (rs.next()) {
return rs.getInt(1) > 0;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DatabaseConnection.close(conn, pstmt, rs);
}
return false;
}

@Override
public User findById(int id) {
String sql = “SELECT * FROM users WHERE id = ?”;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;

try {
conn = DatabaseConnection.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
rs = pstmt.executeQuery();

if (rs.next()) {
User user = new User();
user.setId(rs.getInt(“id”));
user.setUsername(rs.getString(“username”));
user.setPassword(rs.getString(“password”));
user.setEmail(rs.getString(“email”));
user.setCreateTime(rs.getTimestamp(“create_time”));
user.setActive(rs.getBoolean(“active”));
return user;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DatabaseConnection.close(conn, pstmt, rs);
}
return null;
}

@Override
public List findAll() {
List users = new ArrayList<>();
String sql = “SELECT * FROM users ORDER BY create_time DESC”;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try {
conn = DatabaseConnection.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);

while (rs.next()) {
User user = new User();
user.setId(rs.getInt(“id”));
user.setUsername(rs.getString(“username”));
user.setPassword(rs.getString(“password”));
user.setEmail(rs.getString(“email”));
user.setCreateTime(rs.getTimestamp(“create_time”));
user.setActive(rs.getBoolean(“active”));
users.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DatabaseConnection.close(conn, stmt, rs);
}
return users;
}
}
3. JSP页面实现
register.jsp (注册页面)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>



用户注册


用户注册

<%-- 处理注册请求 --%>


<%-- 从请求参数设置属性 --%>


<%-- 调用服务注册 --%>


注册成功!立即登录


注册失败:${result}



<%-- 注册表单 --%>



*


*


*


已有账号?立即登录



login.jsp (登录页面)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>



用户登录


用户登录

<%-- 处理登录请求 --%>



<%-- 登录成功,创建会话 --%>


登录成功!进入主页


用户名或密码错误



<%-- 登录表单 --%>




没有账号?立即注册



welcome.jsp (欢迎页面)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<%-- 检查会话有效性 --%>





欢迎页面


🎉 欢迎回来,${userSession.user.username}!



logout.jsp (退出登录)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%-- 销毁会话 --%>


<% session.invalidate(); %>




已退出


✓ 退出成功

您已安全退出系统

返回登录页



4. 数据库初始化脚本
CREATE DATABASE IF NOT EXISTS userdb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE userdb;

CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
password VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
active BOOLEAN DEFAULT TRUE,
INDEX idx_username (username)
) ENGINE=InnoDB;

— 测试数据
INSERT INTO users (username, password, email) VALUES
(‘admin’, ‘ENC_-1155400445’, ‘admin@example.com’),
(‘test’, ‘ENC_-1155400445’, ‘test@example.com’);
5. web.xml配置

User Management System



30



login.jsp



404
/error/404.jsp


500
/error/500.jsp


高级实战技巧与优化策略
1. 连接池优化
使用DBCP连接池
// DatabaseConnection.java 改进版
package com.example.service;

import org.apache.commons.dbcp2.BasicDataSource;
import java.sql.*;

public class DatabaseConnection {
private static BasicDataSource dataSource;

static {
dataSource = new BasicDataSource();
dataSource.setUrl(“jdbc:mysql://localhost:3306/userdb?useSSL=false&serverTimezone=UTC”);
dataSource.setUsername(“root”);
dataSource.setPassword(“password”);
dataSource.setDriverClassName(“com.mysql.cj.jdbc.Driver”);

// 连接池配置
dataSource.setInitialSize(5);
dataSource.setMaxTotal(20);
dataSource.setMaxIdle(10);
dataSource.setMinIdle(5);
dataSource.setMaxWaitMillis(30000);
dataSource.setValidationQuery(“SELECT 1”);
dataSource.setTestWhileIdle(true);
dataSource.setTimeBetweenEvictionRunsMillis(60000);
}

public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}

public static void close(Connection conn, Statement stmt, ResultSet rs) {
try { if (rs != null) rs.close(); } catch (SQLException e) {}
try { if (stmt != null) stmt.close(); } catch (SQLException e) {}
try { if (conn != null) conn.close(); } catch (SQLException e) {}
}
}
2. 异常处理策略
自定义异常类
package com.example.exception;

public class UserException extends Exception {
private String errorCode;

public UserException(String message, String errorCode) {
super(message);
this.errorCode = errorCode;
}

public String getErrorCode() {
return errorCode;
}
}
改进的UserService
package com.example.service;

import com.example.model.User;
import com.example.dao.UserDAO;
import com.example.dao.UserDAOImpl;
import com.example.exception.UserException;

public class UserService {
private UserDAO userDAO;

public UserService() {
this.userDAO = new UserDAOImpl();
}

public void registerUser(User user) throws UserException {
if (user == null || !user.isValid()) {
throw new UserException(“用户数据无效”, “INVALID_USER_DATA”);
}

if (userDAO.usernameExists(user.getUsername())) {
throw new UserException(“用户名已存在”, “USERNAME_EXISTS”);
}

user.encryptPassword();

if (!userDAO.save(user)) {
throw new UserException(“注册失败,请稍后重试”, “REGISTRATION_FAILED”);
}
}

public User loginUser(String username, String password) throws UserException {
if (username == null || password == null) {
throw new UserException(“用户名和密码不能为空”, “MISSING_CREDENTIALS”);
}

User user = userDAO.findByUsername(username);
if (user == null) {
throw new UserException(“用户不存在”, “USER_NOT_FOUND”);
}

if (!user.checkPassword(password)) {
throw new UserException(“密码错误”, “INVALID_PASSWORD”);
}

if (!user.isActive()) {
throw new UserException(“账户已被禁用”, “ACCOUNT_DISABLED”);
}

return user;
}
}
3. JSP错误处理页面
error/500.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>



系统错误


500

服务器内部错误

错误信息:${pageContext.exception.message}
错误类型:${pageContext.exception.class.name}

返回上一页
返回首页



4. 性能监控与调试
调试Bean
package com.example.util;

import java.util.HashMap;
import java.util.Map;

public class DebugBean {
private static final Map methodTimings = new HashMap<>();
private static final Map methodCalls = new HashMap<>();

public static void recordTiming(String methodName, long duration) {
methodTimings.put(methodName, duration);
methodCalls.put(methodName, methodCalls.getOrDefault(methodName, 0) + 1);
}

public static String getStats() {
StringBuilder sb = new StringBuilder();
sb.append(“Method Performance Stats:\n”);
for (String method : methodTimings.keySet()) {
sb.append(String.format(“%s: %d calls, avg: %d ms\n”,
method,
methodCalls.get(method),
methodTimings.get(method) / methodCalls.get(method)));
}
return sb.toString();
}

public static void reset() {
methodTimings.clear();
methodCalls.clear();
}
}
在DAO中使用
public class UserDAOImpl implements UserDAO {
@Override
public User findByUsername(String username) {
long start = System.currentTimeMillis();
// … 原有代码 …
long duration = System.currentTimeMillis() – start;
DebugBean.recordTiming(“UserDAO.findByUsername”, duration);
return user;
}
}
完整案例:电商产品管理系统
1. 产品管理JavaBean体系
Product.java
package com.example.model;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;

public class Product implements Serializable {
private static final long serialVersionUID = 1L;

private int id;
private String name;
private String description;
private BigDecimal price;
private int stock;
private String category;
private String imageUrl;
private boolean active;
private Date createTime;
private Date updateTime;

public Product() {}

// Builder模式构造器
public static class Builder {
private String name;
private BigDecimal price;
private int stock;
private String category;
private String description;
private String imageUrl;

public Builder name(String name) { this.name = name; return this; }
public Builder price(BigDecimal price) { this.price = price; return this; }
public Builder stock(int stock) { this.stock = stock; return this; }
public Builder category(String category) { this.category = category; return this; }
public Builder description(String description) { this.description = description; return this; }
public Builder imageUrl(String imageUrl) { this.imageUrl = imageUrl; return this; }

public Product build() {
Product product = new Product();
product.name = this.name;
product.price = this.price;
product.stock = this.stock;
product.category = this.category;
product.description = this.description;
product.imageUrl = this.imageUrl;
product.active = true;
product.createTime = new Date();
product.updateTime = new Date();
return product;
}
}

// Getters and Setters
public int getId() { return id; }
public void setId(int id) { this.id = id; this.updateTime = new Date(); }

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

public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; this.updateTime = new Date(); }

public BigDecimal getPrice() { return price; }
public void setPrice(BigDecimal price) { this.price = price; this.updateTime = new Date(); }

public int getStock() { return stock; }
public void setStock(int stock) { this.stock = stock; this.updateTime = new Date(); }

public String getCategory() { return category; }
public void setCategory(String category) { this.category = category; this.updateTime = new Date(); }

public String getImageUrl() { return imageUrl; }
public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; this.updateTime = new Date(); }

public boolean isActive() { return active; }
public void setActive(boolean active) { this.active = active; this.updateTime = new Date(); }

public Date getCreateTime() { return createTime; }
public void setCreateTime(Date createTime) { this.createTime = createTime; }

public Date getUpdateTime() { return updateTime; }
public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; }

// 业务方法
public boolean isInStock() {
return stock > 0;
}

public void decreaseStock(int quantity) {
if (stock >= quantity) {
stock -= quantity;
this.updateTime = new Date();
}
}

public BigDecimal calculateTotalPrice(int quantity) {
return price.multiply(new BigDecimal(quantity));
}

@Override
public String toString() {
return “Product [id=” + id + “, name=” + name + “, price=” + price + “, stock=” + stock + “]”;
}
}
ProductService.java
package com.example.service;

import com.example.model.Product;
import com.example.dao.ProductDAO;
import com.example.dao.ProductDAOImpl;
import com.example.exception.ProductException;
import java.util.List;

public class ProductService {
private ProductDAO productDAO;

public ProductService() {
this.productDAO = new ProductDAOImpl();
}

// 创建产品
public void createProduct(Product product) throws ProductException {
if (product == null || product.getName() == null || product.getName().trim().isEmpty()) {
throw new ProductException(“产品名称不能为空”, “INVALID_PRODUCT_DATA”);
}
if (product.getPrice() == null || product.getPrice().doubleValue() <= 0) { throw new ProductException("产品价格必须大于0", "INVALID_PRICE"); } if (product.getStock() < 0) { throw new ProductException("库存不能为负数", "INVALID_STOCK"); } if (!productDAO.save(product)) { throw new ProductException("创建产品失败", "CREATE_FAILED"); } } // 更新产品 public void updateProduct(Product product) throws ProductException { if (product == null || product.getId() <= 0) { throw new ProductException("产品ID无效", "INVALID_ID"); } if (!productDAO.update(product)) { throw new ProductException("更新产品失败", "UPDATE_FAILED"); } } // 获取产品列表(带分页) public List getProducts(int page, int pageSize, String category) {
int offset = (page – 1) * pageSize;
return productDAO.findAll(offset, pageSize, category);
}

// 获取产品详情
public Product getProduct(int id) throws ProductException {
Product product = productDAO.findById(id);
if (product == null) {
throw new ProductException(“产品不存在”, “PRODUCT_NOT_FOUND”);
}
return product;
}

// 扣减库存
public void decreaseStock(int productId, int quantity) throws ProductException {
Product product = getProduct(productId);
if (!product.isInStock() || product.getStock() < quantity) { throw new ProductException("库存不足", "INSUFFICIENT_STOCK"); } product.decreaseStock(quantity); updateProduct(product); } // 搜索产品 public List searchProducts(String keyword) {
return productDAO.search(keyword);
}
}
2. 产品管理JSP页面
product-list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<%-- 获取查询参数 --%>



<%-- 获取产品列表 --%>










产品列表


产品管理系统

<%-- 搜索框 --%>

<%-- 产品列表 --%>

${fn:escapeXml(product.name)}
${product.category}
库存:

充足 (${product.stock})
紧张 (${product.stock})
缺货

<%-- 分页 --%>


暂无产品数据

添加第一个产品


添加新产品



product-add.jsp (产品添加)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<%-- 处理表单提交 --%>

<%-- 设置属性 --%>



<%-- 转换价格和库存 --%>


<%-- 调用服务 --%>





添加失败:${exception.message}





添加产品


添加新产品










取消



最佳实践与性能优化
1. 代码组织最佳实践
分层架构清晰
Controller (JSP) → Service (JavaBean) → DAO (JavaBean) → Database
命名规范
JavaBean类名:名词,首字母大写(如
User
,
ProductService
)
JSP页面:小写+连字符(如
user-list.jsp
,
product-add.jsp
)
包名:全小写,反向域名(如
com.example.model
)
2. 安全最佳实践
输入验证
// 在UserService中添加
public String sanitizeInput(String input) {
if (input == null) return null;
return input.replaceAll(“[<>\”‘]”, “”); // 简单XSS防护
}
会话固定攻击防护
<%-- 在登录成功后 --%>
<% session.invalidate(); session = request.getSession(true); // 创建新会话 %>
3. 性能优化技巧
延迟加载
// 在ProductService中
public Product getProductWithDetails(int id) {
Product product = productDAO.findById(id);
if (product != null) {
// 延迟加载关联数据
product.setReviews(reviewDAO.findByProductId(id));
}
return product;
}
缓存策略
// 简单缓存实现
public class ProductCache {
private static final Map cache = new ConcurrentHashMap<>();
private static final long CACHE_EXPIRY = 5 * 60 * 1000; // 5分钟
private static final Map timestamps = new ConcurrentHashMap<>();

public static Product get(int id) {
Long timestamp = timestamps.get(id);
if (timestamp != null && System.currentTimeMillis() – timestamp < CACHE_EXPIRY) { return cache.get(id); } return null; } public static void put(int id, Product product) { cache.put(id, product); timestamps.put(id, System.currentTimeMillis()); } } 4. 测试策略 单元测试示例 // 使用JUnit测试UserService import org.junit.Test; import static org.junit.Assert.*; public class UserServiceTest { @Test public void testRegisterUser() throws UserException { UserService service = new UserService(); User user = new User("testuser", "password123", "test@example.com"); // 测试正常注册 service.registerUser(user); User saved = service.loginUser("testuser", "password123"); assertNotNull(saved); assertEquals("testuser", saved.getUsername()); } @Test(expected = UserException.class) public void testRegisterDuplicateUser() throws UserException { UserService service = new UserService(); User user1 = new User("duplicate", "pass123", "user1@example.com"); User user2 = new User("duplicate", "pass456", "user2@example.com"); service.registerUser(user1); service.registerUser(user2); // 应抛出异常 } } 总结 JSP与JavaBean的结合为动态网站开发提供了强大而灵活的解决方案。通过本文的详细讲解和完整案例,您应该掌握了: 核心概念 :JavaBean规范、JSP动作标签、EL表达式 架构设计 :分层架构、MVC模式的早期实现 实战技巧 :连接池、异常处理、性能监控 安全实践 :输入验证、会话管理 优化策略 :缓存、延迟加载、代码组织 这种架构虽然在现代开发中逐渐被Spring MVC等框架取代,但其核心思想和设计模式仍然具有重要价值。对于维护遗留系统或快速开发中小型项目,JSP+JavaBean依然是一个可靠的选择。 关键要点回顾 : 严格遵循JavaBean规范 保持业务逻辑与页面展示分离 使用连接池提升性能 实现完善的异常处理机制 注重安全性和可维护性 希望本文能帮助您在实际项目中更好地应用JSP与JavaBean技术,构建高质量的动态网站应用。