JSP动态网页开发实战:从数据库交互到HTML渲染全解析

张开发
2026/4/7 19:07:56 15 分钟阅读

分享文章

JSP动态网页开发实战:从数据库交互到HTML渲染全解析
1. JSP动态网页开发入门指南第一次接触JSP动态网页开发时我也被那些专业术语搞得晕头转向。后来在实际项目中摸爬滚打才发现JSP其实就是把Java代码嵌入HTML的技术。想象一下你正在写一个电商网站商品列表需要从数据库实时获取数据这时候静态HTML就无能为力了而JSP可以完美解决这个问题。动态网页和静态网页最大的区别就在于活数据。比如天气预报网站如果每天手动修改HTML代码显然不现实。JSP通过服务器端处理能够自动生成包含最新天气数据的HTML页面。我刚开始做项目时就遇到过需要显示实时库存的需求正是JSP帮了大忙。2. 搭建JSP开发环境2.1 基础环境配置工欲善其事必先利其器。搭建JSP开发环境需要准备三样东西JDK、Tomcat服务器和IDE工具。我推荐使用Eclipse或者IntelliJ IDEA它们对JSP开发支持都很友好。记得第一次配置环境时我忘了设置JAVA_HOME环境变量结果折腾了半天才发现问题所在。安装完JDK后需要下载Tomcat服务器。建议选择8.5或9.0版本稳定性比较好。解压后要配置CATALINA_HOME环境变量这个步骤很多新手容易忽略。配置完成后可以在bin目录下运行startup.bat(Windows)或startup.sh(Linux/Mac)来启动服务器。2.2 创建第一个JSP项目在IDE中新建Dynamic Web Project时记得勾选Generate web.xml选项。我建议项目结构按照Maven标准来组织src └── main ├── java ├── resources └── webapp ├── WEB-INF └── index.jsp创建第一个JSP页面时可以在webapp目录下新建index.jsp文件。基础模板长这样% page contentTypetext/html;charsetUTF-8 languagejava % html head title我的第一个JSP页面/title /head body % out.println(Hello World!); % /body /html3. JSP与数据库交互实战3.1 数据库连接配置JSP连接数据库通常使用JDBC。我习惯把数据库配置放在WEB-INF目录下的context.xml中Context Resource namejdbc/myDB authContainer typejavax.sql.DataSource maxTotal100 maxIdle30 maxWaitMillis10000 usernameroot password123456 driverClassNamecom.mysql.jdbc.Driver urljdbc:mysql://localhost:3306/testDB/ /Context在JSP页面中获取连接时我推荐使用JNDI查找方式% Context ctx new InitialContext(); DataSource ds (DataSource)ctx.lookup(java:comp/env/jdbc/myDB); Connection conn ds.getConnection(); %3.2 数据库CRUD操作查询数据是最常见的操作。我通常会封装一个JavaBean来处理public class ProductDAO { public ListProduct getAllProducts() throws SQLException { ListProduct products new ArrayList(); try (Connection conn getConnection(); Statement stmt conn.createStatement(); ResultSet rs stmt.executeQuery(SELECT * FROM products)) { while (rs.next()) { Product p new Product(); p.setId(rs.getInt(id)); p.setName(rs.getString(name)); p.setPrice(rs.getDouble(price)); products.add(p); } } return products; } }在JSP页面中调用这个DAO% page importcom.example.dao.ProductDAO % % page importcom.example.model.Product % % ProductDAO dao new ProductDAO(); ListProduct products dao.getAllProducts(); %4. JSP页面渲染技巧4.1 JSP标准标签库(JSTL)使用JSTL能让你的JSP代码更简洁。首先需要在页面头部引入标签库% taglib prefixc urihttp://java.sun.com/jsp/jstl/core %遍历产品列表时使用JSTL比Scriptlet优雅多了table tr thID/th th名称/th th价格/th /tr c:forEach items${products} varproduct tr td${product.id}/td td${product.name}/td td${product.price}/td /tr /c:forEach /table4.2 EL表达式优化EL(Expression Language)可以进一步简化代码。比如处理空值p欢迎您${not empty user ? user.name : 游客}/p我经常用EL来处理表单回显input typetext nameusername value${param.username}5. 项目实战用户管理系统5.1 系统架构设计一个典型的用户管理系统包含以下功能模块用户登录/注销用户列表展示用户信息增删改查权限控制我建议采用分层架构表示层(JSP) ↓ 控制层(Servlet) ↓ 服务层(Service) ↓ 数据访问层(DAO) ↓ 数据库5.2 关键代码实现用户登录Servlet示例WebServlet(/login) public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username request.getParameter(username); String password request.getParameter(password); UserService service new UserService(); User user service.login(username, password); if(user ! null) { request.getSession().setAttribute(currentUser, user); response.sendRedirect(welcome.jsp); } else { request.setAttribute(error, 用户名或密码错误); request.getRequestDispatcher(login.jsp).forward(request, response); } } }对应的登录页面login.jspform actionlogin methodpost div classform-group label用户名/label input typetext nameusername required /div div classform-group label密码/label input typepassword namepassword required /div button typesubmit登录/button c:if test${not empty error} div classerror${error}/div /c:if /form6. 性能优化与安全实践6.1 性能调优技巧数据库连接池配置对性能影响很大。这是我的常用配置Resource namejdbc/myDB ... maxTotal100 maxIdle30 minIdle10 maxWaitMillis10000 validationQuerySELECT 1 testOnBorrowtrue removeAbandonedOnBorrowtrue removeAbandonedTimeout60/JSP页面缓存也很重要% page buffer16kb autoFlushtrue %6.2 安全防护措施SQL注入是最常见的安全威胁。我强烈建议使用PreparedStatementpublic User getUserById(int id) throws SQLException { String sql SELECT * FROM users WHERE id ?; try (Connection conn getConnection(); PreparedStatement stmt conn.prepareStatement(sql)) { stmt.setInt(1, id); try (ResultSet rs stmt.executeQuery()) { if (rs.next()) { User user new User(); user.setId(rs.getInt(id)); user.setUsername(rs.getString(username)); return user; } } } return null; }密码存储一定要加密。我通常用BCryptimport org.mindrot.jbcrypt.BCrypt; String hashed BCrypt.hashpw(rawPassword, BCrypt.gensalt()); if (BCrypt.checkpw(candidatePassword, hashed)) { // 密码匹配 }7. 常见问题排查7.1 中文乱码问题遇到中文乱码时我通常会检查三个地方JSP页面头部字符集设置% page contentTypetext/html;charsetUTF-8 languagejava %请求编码过滤public class EncodingFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding(UTF-8); response.setCharacterEncoding(UTF-8); chain.doFilter(request, response); } }数据库连接字符串jdbc:mysql://localhost:3306/testDB?useUnicodetruecharacterEncodingUTF-87.2 页面跳转问题重定向和转发的区别经常让人困惑重定向是客户端行为地址栏会变response.sendRedirect(welcome.jsp);转发是服务器行为地址栏不变request.getRequestDispatcher(welcome.jsp).forward(request, response);我在项目中遇到过因为混淆两者导致的表单重复提交问题后来统一使用Post-Redirect-Get模式解决了。

更多文章