关于“enctype=multipart/form-data”之后使用request.getParameter为null的解决

博客讲述了文字和图片上传时出现空指针异常的问题,取消图片上传、只传文字为 null 时上传成功。经百度得知是题目相关问题,常见解决方法是 upload 方法或输入流取值等,但作者看不懂。查看以前代码后,添加 @MultipartConfig 解决了问题。

首先是正常输入文字和图片提交之后空指针异常,取消图片上传(因为数据库设置可以为空),只上传文字为null,如下:

上传成功后

百度之后知道是题目相关的问题,然后基本解决方法都是什么upload方法或者其他的输入流取值等。

但是由于我是个菜鸡中的菜鸡非常菜的那种,看不懂很多人的解决方式,而且之前在学校写过类似的就可以正常上传,看了以前的代码之后发现少了@MultipartConfig

加上了之后成功获取,包括之前的空指针异常也解决了。完美!

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.sql.*" %> <%@ page import="com.yourproject.util.FileUploadUtil" %> <%@ page import="jakarta.servlet.http.Part" %> <%@ include file="db.jsp" %> <%! // 辅助方法:安全解析数值 private Integer safeParseInt(String value) { if (value == null || value.trim().isEmpty()) return null; try { return Integer.parseInt(value.trim()); } catch (NumberFormatException e) { return null; } } private Double safeParseDouble(String value) { if (value == null || value.trim().isEmpty()) return null; try { return Double.parseDouble(value.trim()); } catch (NumberFormatException e) { return null; } } %> <% // ====================== 功能处理部分 ====================== String action = request.getParameter("action"); String currentTab = request.getParameter("currentTab") != null ? request.getParameter("currentTab") : "pet-management"; String message = null; String messageType = null; // 获取宠物信息(编辑模式) String title = null; Integer category = null; String tag = null; String photo = null; Double price = null; Integer stock = null; String descs = null; // 宠物描述 String petId = null; if ("edit".equals(action)) { petId = request.getParameter("id"); if (petId != null && !petId.isEmpty()) { try (PreparedStatement stmt = conn.prepareStatement("SELECT * FROM pets WHERE id = ?")) { stmt.setInt(1, Integer.parseInt(petId)); ResultSet rs = stmt.executeQuery(); if (rs.next()) { title = rs.getString("title"); category = rs.getInt("category"); tag = rs.getString("tag"); photo = rs.getString("photo"); price = rs.getDouble("price"); stock = rs.getInt("stock"); descs = rs.getString("descs"); } } catch (NumberFormatException | SQLException e) { message = "加载宠物信息失败: " + e.getMessage(); messageType = "error"; e.printStackTrace(); } } } // 处理表单提交(支持文件上传) if ("POST".equals(request.getMethod())) { // 获取普通表单字段 petId = request.getParameter("pet-id"); title = request.getParameter("pet-name"); String categoryStr = request.getParameter("pet-category"); tag = request.getParameter("pet-tags"); String priceStr = request.getParameter("pet-price"); String stockStr = request.getParameter("pet-stock"); descs = request.getParameter("pet-description"); // 对应表单里的name="pet-description" // 调试输出 System.out.println("Form Data:"); System.out.println("title: " + title); System.out.println("category: " + categoryStr); System.out.println("price: " + priceStr); System.out.println("stock: " + stockStr); System.out.println("descs: " + descs); // 解析数值字段 Integer categoryInt = safeParseInt(categoryStr); Double priceDbl = safeParseDouble(priceStr); Integer stockInt = safeParseInt(stockStr); // 验证必需字段 if (title == null || title.trim().isEmpty()) { message = "请填写宠物名称"; messageType = "error"; } else if (categoryInt == null) { message = "请选择分类"; messageType = "error"; } else if (priceDbl == null || priceDbl <= 0) { message = "请输入有效的价格"; messageType = "error"; } else if (stockInt == null || stockInt < 0) { message = "请输入有效的库存数量"; messageType = "error"; } else if (descs == null || descs.trim().isEmpty()) { // 校验宠物描述 message = "请填写宠物描述"; messageType = "error"; } else { try { // 处理文件上传 Part filePart = request.getPart("pet-photo-file"); String existingPhoto = request.getParameter("existing-photo"); String newPhoto = null; if (filePart != null && filePart.getSize() > 0) { // 上传新图片 String contextPath = request.getServletContext().getRealPath("/"); newPhoto = FileUploadUtil.uploadImage(filePart, contextPath); // 删除旧图片(编辑模式且存在旧图片) if ("edit".equals(action) && existingPhoto != null && !existingPhoto.isEmpty()) { FileUploadUtil.deleteImage(existingPhoto, contextPath); } } // 确定使用的照片URL String finalPhoto = (newPhoto != null) ? newPhoto : existingPhoto; if ("add".equals(action)) { // 添加新宠物 String sql = "INSERT INTO pets (category, title, tag, photo, price, stock, descs, ondate) " + "VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_DATE())"; try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { stmt.setInt(1, categoryInt); stmt.setString(2, title.trim()); stmt.setString(3, tag != null ? tag.trim() : ""); stmt.setString(4, finalPhoto != null ? finalPhoto : ""); stmt.setDouble(5, priceDbl); stmt.setInt(6, stockInt); stmt.setString(7, descs.trim()); int affectedRows = stmt.executeUpdate(); if (affectedRows > 0) { response.sendRedirect("admin.jsp?currentTab=" + currentTab); return; } else { message = "添加宠物失败,请重试"; messageType = "error"; } } } else if ("edit".equals(action) && petId != null) { // 更新宠物 String sql = "UPDATE pets SET category = ?, title = ?, tag = ?, " + "photo = ?, price = ?, stock = ?, descs = ? WHERE id = ?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, categoryInt); stmt.setString(2, title.trim()); stmt.setString(3, tag != null ? tag.trim() : ""); stmt.setString(4, finalPhoto != null ? finalPhoto : ""); stmt.setDouble(5, priceDbl); stmt.setInt(6, stockInt); stmt.setString(7, descs.trim()); stmt.setInt(8, Integer.parseInt(petId)); int affectedRows = stmt.executeUpdate(); if (affectedRows > 0) { response.sendRedirect("admin.jsp?currentTab=" + currentTab); return; } else { message = "未找到要更新的宠物或数据未更改"; messageType = "error"; } } } } catch (SQLException e) { message = "数据库操作失败: " + e.getMessage(); messageType = "error"; e.printStackTrace(); } catch (Exception e) { message = "操作失败: " + e.getMessage(); messageType = "error"; e.printStackTrace(); } } } %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title><%= "add".equals(action) ? "添加宠物" : "编辑宠物" %> - 管理员中心</title> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f5f5f5; } .container { max-width: 800px; margin: 0 auto; background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); } h1 { color: #006D77; border-bottom: 2px solid #D4B483; padding-bottom: 10px; } .form-group { margin-bottom: 20px; } label { display: block; margin-bottom: 5px; font-weight: bold; color: #006D77; } input[type="text"], input[type="number"], select, textarea { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; font-size: 16px; } textarea { height: 150px; resize: vertical; } .btn-group { display: flex; gap: 10px; margin-top: 20px; } .btn { padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; font-weight: bold; } .btn-primary { background-color: #006D77; color: white; } .btn-secondary { background-color: #6c757d; color: white; } .message { padding: 10px; margin-bottom: 20px; border-radius: 4px; } .required:after { content: " *"; color: red; } </style> </head> <body> <div class="container"> <h1><%= "add".equals(action) ? "添加新宠物" : "编辑宠物信息" %></h1> <% if (message != null) { %> <div class="message <%= messageType %>"><%= message %></div> <% } %> <form method="POST" action="adminpet.jsp?action=<%= action %>&currentTab=<%= currentTab %>" enctype="multipart/form-data"> <% if ("edit".equals(action)) { %> <input type="hidden" name="pet-id" value="<%= petId %>"> <% } %> <div class="form-group"> <label for="pet-name" class="required">宠物名称</label> <input type="text" id="pet-name" name="pet-name" value="<%= title != null ? title : (request.getParameter("pet-name") != null ? request.getParameter("pet-name") : "") %>" required> </div> <div class="form-group"> <label for="pet-category" class="required">分类</label> <select id="pet-category" name="pet-category" required> <option value="">-- 请选择分类 --</option> <% try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM category ORDER BY id")) { while (rs.next()) { int catId = rs.getInt("id"); String catName = rs.getString("name"); String petCategoryParam = request.getParameter("pet-category"); boolean selected = (category != null && catId == category) || (petCategoryParam != null && !petCategoryParam.isEmpty() && catId == Integer.parseInt(petCategoryParam)); %> <option value="<%= catId %>" <%= selected ? "selected" : "" %>> <%= catName %> </option> <% } } catch (SQLException e) { e.printStackTrace(); } %> </select> </div> <div class="form-group"> <label for="pet-price" class="required">价格</label> <input type="number" id="pet-price" name="pet-price" min="0.01" step="0.01" value="<%= price != null ? price : (request.getParameter("pet-price") != null ? request.getParameter("pet-price") : "") %>" required> </div> <div class="form-group"> <label for="pet-stock" class="required">库存数量</label> <input type="number" id="pet-stock" name="pet-stock" min="0" value="<%= stock != null ? stock : (request.getParameter("pet-stock") != null ? request.getParameter("pet-stock") : "") %>" required> </div> <div class="form-group"> <label for="pet-tags">特点</label> <input type="text" id="pet-tags" name="pet-tags" value="<%= tag != null ? tag : (request.getParameter("pet-tags") != null ? request.getParameter("pet-tags") : "") %>" placeholder="用逗号分隔多个标签"> </div> <div class="form-group"> <label for="pet-photo-file">宠物图片</label> <input type="file" id="pet-photo-file" name="pet-photo-file" accept="image/*"> <% if (photo != null && !photo.isEmpty()) { %> <div style="margin-top: 10px;"> <img src="<%= photo %>" alt="当前宠物图片" style="max-width: 200px; max-height: 200px;"> <input type="hidden" name="existing-photo" value="<%= photo %>"> </div> <% } %> </div> <div class="form-group"> <label for="pet-description" class="required">宠物描述</label> <textarea id="pet-description" name="pet-description" required><%= descs != null ? descs : (request.getParameter("pet-description") != null ? request.getParameter("pet-description") : "") %></textarea> </div> <div class="btn-group"> <button type="submit" class="btn btn-primary">保存</button> <button type="button" class="btn btn-secondary" onclick="location.href='admin.jsp?currentTab=<%= currentTab %>'">取消</button> </div> </form> </div> </body> </html>
06-23
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值