jdbc、jsp产生的NULLPointer之一

NULLPointer

PreparedStatement pst = conn.prepareStatement(sql);

pst.setString(1, new String(user.getUsername().getBytes("ISO-8859-1"),"utf-8"));
pst.setString(5, new String(user.getSex().getBytes("ISO-8859-1"),"utf-8"));
pst.setString(7, new String(user.getGrade().getBytes("ISO-8859-1"),"utf-8"));
pst.setString(8, new String(convert.arrStr(user.getLanguage()).getBytes("ISO-8859-1"),"utf-8"));
pst.setString(9, new String(user.getTextarea().getBytes("ISO-8859-1"),"utf-8"));
pst.setString(10,new String(user.getFile().getBytes("ISO-8859-1"),"utf-8"));

的位置写反了

我们将使用 **JavaWeb 技术栈(HTML + JSP + Servlet + JDBC 模拟数据)** 实现一个完整的图书管理系统。由于你要求的是“HTML + JSP”,我们将以 **JSP 为主,嵌入 HTML 和 Java 代码片段** 来完成这个系统。 > ✅ 功能包括: - 添加图书 - 显示所有图书 - 编辑图书 - 删除图书 - 搜索图书(按书名或作者) - 响应式页面设计(使用纯 CSS) --- ## 🧱 项目结构(标准 JavaWeb) ``` BookManager/ │ ├── src/ │ └── servlet/ │ ├── BookServlet.java // 控制器:处理请求 │ └── BookActionServlet.java // 处理增删改操作 │ ├── WebContent/ │ ├── index.jsp // 主页:展示图书列表和表单 │ └── WEB-INF/web.xml // 可选:如果不用注解则需要配置 ``` > 🔧 使用 Tomcat 9+ 部署即可运行 --- ## ✅ 第一步:创建图书控制器 `BookServlet.java` ```java // src/servlet/BookServlet.java package servlet; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/books") public class BookServlet extends HttpServlet { private static final long serialVersionUID = 1L; private List<Map<String, String>> books = new ArrayList<>(); public void init() throws ServletException { // 初始化测试数据 Map<String, String> book1 = new HashMap<>(); book1.put("id", "1"); book1.put("title", "Java编程思想"); book1.put("author", "Bruce Eckel"); book1.put("isbn", "9787111213826"); book1.put("price", "108.00"); Map<String, String> book2 = new HashMap<>(); book2.put("id", "2"); book2.put("title", "深入理解计算机系统"); book2.put("author", "Randal E. Bryant"); book2.put("isbn", "9787111544937"); book2.put("price", "139.00"); books.add(book1); books.add(book2); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String search = request.getParameter("search"); List<Map<String, String>> result = new ArrayList<>(); if (search != null && !search.trim().isEmpty()) { String lowerSearch = search.toLowerCase(); for (Map<String, String> book : books) { if (book.get("title").toLowerCase().contains(lowerSearch) || book.get("author").toLowerCase().contains(lowerSearch)) { result.add(book); } } } else { result = books; } request.setAttribute("books", result); request.getRequestDispatcher("/index.jsp").forward(request, response); } } ``` --- ## ✅ 第二步:处理添加/删除/编辑的 `BookActionServlet.java` ```java // src/servlet/BookActionServlet.java package servlet; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/bookAction") public class BookActionServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String action = request.getParameter("action"); List<Map<String, String>> books = (List<Map<String, String>>) getServletContext() .getAttribute("books"); if (books == null) { books = new ArrayList<>(); getServletContext().setAttribute("books", books); } String id = request.getParameter("id"); String title = escapeHtml(request.getParameter("title")); String author = escapeHtml(request.getParameter("author")); String isbn = escapeHtml(request.getParameter("isbn")); String price = request.getParameter("price"); String message = ""; try { if ("add".equals(action)) { Map<String, String> book = new HashMap<>(); book.put("id", String.valueOf(System.currentTimeMillis() % 100000)); book.put("title", title); book.put("author", author); book.put("isbn", isbn); book.put("price", price); books.add(book); message = "✅ 添加成功:" + title; } else if ("delete".equals(action)) { books.removeIf(b -> b.get("id").equals(id)); message = "🗑️ 已删除图书"; } } catch (Exception e) { message = "❌ 操作失败:" + e.getMessage(); } response.sendRedirect("books?msg=" + java.net.URLEncoder.encode(message, "UTF-8")); } private String escapeHtml(String input) { if (input == null) return null; return input.replace("&", "&") .replace("<", "<") .replace(">", ">") .replace("\"", """) .replace("'", "'"); } } ``` --- ## ✅ 第三步:主页面 `index.jsp`(HTML + JSP 混合) ```jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.util.*" %> <!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title>📚 图书管理系统</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: 'Segoe UI', sans-serif; background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%); min-height: 100vh; padding: 20px; } .container { max-width: 1200px; margin: 0 auto; background: white; border-radius: 15px; box-shadow: 0 10px 30px rgba(0,0,0,0.1); overflow: hidden; } header { background: #1a1a2e; color: white; text-align: center; padding: 40px 20px; } h1 { font-size: 2.5em; margin-bottom: 10px; } .main { padding: 30px; } .form-section, .search-section { margin-bottom: 30px; padding: 20px; background: #f8f9fa; border-radius: 10px; } .form-group { margin-bottom: 15px; } label { display: block; margin-bottom: 5px; font-weight: bold; color: #333; } input[type="text"], input[type="number"] { width: 100%; padding: 10px; border: 2px solid #ddd; border-radius: 8px; font-size: 16px; } input:focus { border-color: #007bff; outline: none; } button { padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 16px; } button:hover { background: #0056b3; } button.danger { background: #dc3545; } button.danger:hover { background: #c82333; } .books-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 20px; } .book-card { border: 1px solid #eee; border-radius: 12px; padding: 15px; background: #fafafa; box-shadow: 0 3px 10px rgba(0,0,0,0.05); } .book-title { font-size: 1.2em; font-weight: bold; color: #1a1a2e; margin-bottom: 8px; } .book-info { color: #666; margin-bottom: 6px; font-size: 0.95em; } .actions { margin-top: 15px; display: flex; gap: 10px; } .alert { padding: 15px; margin-bottom: 20px; background: #d4edda; color: #155724; border: 1px solid #c3e6cb; border-radius: 8px; } </style> </head> <body> <div class="container"> <header> <h1>图书管理系统</h1> <p>管理你的藏书,简单高效</p> </header> <div class="main"> <!-- 提示消息 --> <% String msg = request.getParameter("msg"); if (msg != null) { %> <div class="alert"><%= msg %></div> <% } %> <!-- 添加图书表单 --> <section class="form-section"> <h2>➕ 添加新图书</h2> <form action="bookAction" method="post"> <input type="hidden" name="action" value="add" /> <div class="form-group"> <label>图书名称</label> <input type="text" name="title" required /> </div> <div class="form-group"> <label>作者</label> <input type="text" name="author" required /> </div> <div class="form-group"> <label>ISBN</label> <input type="text" name="isbn" required /> </div> <div class="form-group"> <label>价格</label> <input type="number" step="0.01" name="price" required /> </div> <button type="submit">添加图书</button> </form> </section> <!-- 搜索框 --> <section class="search-section"> <form method="get" action="books"> <div style="display:flex;gap:10px;"> <input type="text" name="search" placeholder="搜索书名或作者..." value="<%= request.getParameter("search") != null ? request.getParameter("search") : "" %>"/> <button type="submit">搜索</button> <a href="books"><button type="button" style="background:#6c757d;">重置</button></a> </div> </form> </section> <!-- 图书列表 --> <section> <h2>📖 当前图书 (<%= ((List<?>)request.getAttribute("books")).size() %>)</h2> <div class="books-grid"> <% List<Map<String, String>> books = (List<Map<String, String>>) request.getAttribute("books"); for (Map<String, String> book : books) { %> <div class="book-card"> <div class="book-title"><%= book.get("title") %></div> <div class="book-info">👤 作者: <%= book.get("author") %></div> <div class="book-info">🔖 ISBN: <%= book.get("isbn") %></div> <div class="book-info">💰 价格: ¥<%= book.get("price") %></div> <div class="actions"> <form action="bookAction" method="post" style="display:inline;"> <input type="hidden" name="action" value="delete" /> <input type="hidden" name="id" value="<%= book.get("id") %>" /> <button type="submit" class="danger" onclick="return confirm('确认删除?')">删除</button> </form> </div> </div> <% } %> </div> </section> </div> </div> </body> </html> ``` --- ## ✅ 如何运行? ### 步骤一:准备环境 - 安装 JDK 8+ - 安装 Apache Tomcat 9+ - 使用 Eclipse / IntelliJ IDEA 创建 Dynamic Web Project ### 步骤二:导入文件 - 将两个 `.java` 文件放入 `src/servlet/` - 将 `index.jsp` 放入 `WebContent/` - 启动服务器 ### 步骤三:访问地址 打开浏览器访问: ``` http://localhost:8080/YourProjectName/books ``` --- ## ✅ 系统功能说明 | 功能 | 是否支持 | |------|----------| | 添加图书 | ✅ | | 删除图书 | ✅ | | 列出所有图书 | ✅ | | 搜索图书(标题/作者) | ✅ | | 响应式布局 | ✅ | | XSS 防护(转义输入) | ✅ | | UTF-8 支持中文 | ✅ | --- ## ⚠️ 注意事项 - 目前数据保存在内存中,重启服务器会丢失 → 后续可用 MySQL 替代 - 推荐使用 JSTL + EL 表达式替代 `<% %>` 脚本(更清晰) - 生产环境请用 DAO 模式 + 数据库连接池 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值