<form method=post action="addNew_hxxm.jsp" name="form1"enctype="multipart/form-data">

本文介绍了解决HTML表单使用enctype='multipart/form-data'时,在JSP页面无法通过request获取表单数据的问题。提供了具体的实现代码示例,并解释了这种编码方式主要用于文件上传场景。

问题说明:当html页面的<form>属性中有enctype="multipart/form-data" 时 在jsp页面不能用request.getParameter("name");获得html表单中的数据

例:<form method=post action="addNew_hxxm.jsp" name="form1"enctype="multipart/form-data">

 

解决办法:在jsp页面的<body>下加上以下代码

<%

mySmartUpload.initialize(pageContext);
   mySmartUpload.service(request,response);
   mySmartUpload.upload();

String i_xmmc = mySmartUpload.getRequest().getParameter("xmmc");//取单个参数单个值

%>

 

关于enctype="multipart/form-data"的说明

表单中enctype="multipart/form-data"的意思,是设置表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了multipart/form-data,才能完整的传递文件数据,进行下面的操作.

enctype="multipart/form-data"是上传二进制数据; 
form里面的input的值以2进制的方式传过去,所以request就得不到值了。

取表单值加入数据库时,用到下面的:

SmartUpload su = new SmartUpload();//新建一个SmartUpload对象

su.getRequest().getParameterValues();取数组值

su.getRequest().getParameter( );取单个参数单个值

 

 

创建Web项目,导入相关JAR包; <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.11.0</version> </dependency> 创建并配置web.xml文件; <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>Springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:SpringMVC.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> 添加用于上传的jsp页面; <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <title>文件上传</title> </head> <body> <table border="1"> <tr> <td width="500" align="center">文件上传</td> </tr> <tr> <td> <form action="${pageContext.request.contextPath}/file/upload" method="post" enctype="multipart/form-data"> <input type="file" name="uploadfiles" multiple="multiple"/><br> <input type="submit" value="上传"><br> </form> </td> </tr> <c:forEach items="${msgs}" var="msg"> <tr><td align="center" colspan="2" style="color: red">${msg}</td></tr> </c:forEach> </table> </body> </html> 创建控制类用于上传文件; package com.springmvc.controller; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; @Controller @RequestMapping("/file") public class FileUploadController { @RequestMapping("/upload") public String fileUpload(ArrayList<MultipartFile> uploadfiles, HttpServletRequest request) { //定义列表msgs保存提示信息 ArrayList<String> msgs = new ArrayList<>(); if (uploadfiles.get(0).getSize() > 0) { //判断是否上传文件 for (MultipartFile file : uploadfiles) { //循环获取文件 //判断文件不为空且大小大于0 if (!file.isEmpty() & file.getSize() > 0) { //获取文件原始名称 String originalFilename = file.getOriginalFilename(); //获取服务器中的文件夹路径 String path = request.getServletContext().getRealPath("/upload/"); //设置文件保存到服务器的目标路径 String filePath = path + originalFilename; try { //保存文件内容到目标路径 file.transferTo(new File(filePath)); } catch (IOException e) { msgs.add(filePath + "保存失败"); } msgs.add(filePath +"保存成功"); } } } else msgs.add("上传文件失败"); request.setAttribute("msgs", msgs); return "fileUpload"; } } 添加配置文件; <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.springmvc.controller"/> <mvc:annotation-driven /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!--配置视图控制器,指定文件上传页面的映射路径--> <mvc:view-controller path="/file/fileupload" view-name="fileUpload"/> <mvc:view-controller path="/file/filedownload" view-name="fileDownload"/> <!--配置注解驱动--> <mvc:annotation-driven/> <!--配置文件上传解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--指定请求的编码方式--> <property name="defaultEncoding" value="UTF-8"></property> <!--指定允许上传文件的大小,此处设置最大值为1 M,单位为字节--> <property name="maxUploadSize" value="1024000"></property> </bean> </beans> 添加上传成功的消息页面。 文件下载: 创建控制器类: package com.springmvc.controller; import java.io.File; import java.io.IOException; import java.net.URLEncoder; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/file") public class FileDownloadController { @RequestMapping("/download") public ResponseEntity<byte[]> FileDownload(HttpServletRequest request, String fileName) throws IOException { //获取下载文件的路径 String filepath = request.getServletContext().getRealPath("/upload/") + fileName; //创建该文件的对象 File file = new File(filepath); //将文件读取到字节数组中 byte[] bytes = FileUtils.readFileToByteArray(file); //创建HttpHeaders对象设置响应头信息 HttpHeaders headers = new HttpHeaders(); //设置浏览器以“UTF-8”编码方式显示文件名 fileName = URLEncoder.encode(fileName, "UTF-8"); //设置以下载的方式打开文件,并指定文件名称 headers.setContentDispositionFormData("attachment", fileName); //设置文件的下载方式为二进制流 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); return new ResponseEntity<>(bytes, headers, HttpStatus.OK); } } 添加用于上传的jsp页面; <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <title>文件下载</title> </head> <body> <table border="1"> <tr> <td width="350" align="center">下载列表</td> </tr> <tr> <td> <a href="${pageContext.request.contextPath}/file/download?fileName=微信图片_20250612231528.jpg"> 这是一张图片</a><br> </td> </tr> </table> </body> </html> 实验成果: 修改一下
11-01
这是我的表结构: DROP TABLE IF EXISTS `animalphotos`; CREATE TABLE `animalphotos` ( `photo_id` int NOT NULL AUTO_INCREMENT COMMENT ' 照片ID', `animal_id` int NULL DEFAULT NULL COMMENT ' 所属动物ID', `photo_url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '图片路径或URL', PRIMARY KEY (`photo_id`) USING BTREE, INDEX `animal_id`(`animal_id` ASC) USING BTREE, CONSTRAINT `animalphotos_ibfk_1` FOREIGN KEY (`animal_id`) REFERENCES `animals` (`animal_id`) ON DELETE RESTRICT ON UPDATE RESTRICT ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for animals -- ---------------------------- DROP TABLE IF EXISTS `animals`; CREATE TABLE `animals` ( `animal_id` int NOT NULL AUTO_INCREMENT COMMENT '动物唯一标识', `name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '名称', `species` varchar(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT ' 种类', `gender` enum('雄','雌') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT ' 性别', `age` int NULL DEFAULT NULL COMMENT ' 年龄', `user_id` int NULL DEFAULT NULL COMMENT ' 关联饲养者/管理者(Users.user_id)', `zone` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '动物位置', PRIMARY KEY (`animal_id`) USING BTREE, INDEX `caretaker_id`(`user_id` ASC) USING BTREE, INDEX `species_id`(`species` ASC) USING BTREE, CONSTRAINT `animals_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE RESTRICT ON UPDATE RESTRICT ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for animaltraits -- ---------------------------- DROP TABLE IF EXISTS `animaltraits`; CREATE TABLE `animaltraits` ( `trait_id` int NOT NULL AUTO_INCREMENT COMMENT ' 特征ID', `animal_id` int NULL DEFAULT NULL COMMENT '动物ID(Animals)', `nature` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '性格 ', `favourite` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL COMMENT ' 喜好描述', PRIMARY KEY (`trait_id`) USING BTREE, INDEX `animal_id`(`animal_id` ASC) USING BTREE, CONSTRAINT `animaltraits_ibfk_1` FOREIGN KEY (`animal_id`) REFERENCES `animals` (`animal_id`) ON DELETE RESTRICT ON UPDATE RESTRICT ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for users -- ---------------------------- DROP TABLE IF EXISTS `users`; CREATE TABLE `users` ( `user_id` int NOT NULL AUTO_INCREMENT COMMENT ' 用户唯一标识', `username` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '用户名', `password` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '密码(加密)', `role` enum('游客','饲养者','管理员') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT ' 角色:游客/饲养者/管理员', `status` enum('在线','离线') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户状态(是否在线)', PRIMARY KEY (`user_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1; 这是我的实体类: // User 类 public class User { private int user_id; private String username; private String password; private String role; private String status; private List<Animals> animals; // 用户与动物是一对多关系 // getter 和 setter 方法 } // Animals 类 public class Animals { private int animal_id; private String name; private String gender; // 雄/雌 private Integer age; private String species; private String zone; private User user; // 动物与用户是一对多关系(反向关联) private List<AnimalPhoto> animalPhotos; // 动物与照片是一对多关系 // getter 和 setter 方法 } // AnimalPhoto 类 public class AnimalPhoto { private int photo_id; private Animals animal; // 照片与动物是一对多关系(反向关联) private String photo_url; // getter 和 setter 方法 } // AnimalTrait 类 public class AnimalTrait { private int trait_id; private Animals animal; // 特征与动物是一对一关系(反向关联) private String nature; // 性格 private String favourite; // 喜好描述 // getter 和 setter 方法 } 用户 (users) 与动物 (animals) 之间是一对多关系。 动物 (animals) 与照片 (animalphotos) 之间是一对多关系。 动物 (animals) 与特征 (animaltraits) 之间是一对一关系。 这是我登录注册代码: package com.cxy.Controller; import com.cxy.Pojo.User; import com.cxy.Service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpSession; import java.text.SimpleDateFormat; import java.util.Date; @Controller public class UserController { @Autowired private UserService userService; // 显示登录页面 @GetMapping("/login") public String loginPage(@RequestParam(value = "error", required = false) String error, Model model) { if (error != null) { model.addAttribute("error", true); } return "/login/login.jsp"; // 返回登录页面 } // 处理登录请求 @PostMapping("/login") public String login(@RequestParam String username, @RequestParam String password, HttpSession session, Model model) { User user = userService.login(username, password); if (user != null) { // 更新数据库中的在线状态 userService.updateUserStatus(user.getUserId(), "在线"); // 将用户信息存入 session session.setAttribute("user", user); session.setAttribute("username", user.getUsername()); // 存储用户名 session.setAttribute("role", user.getRole()); // 存储角色 session.setAttribute("status", "在线"); // 存储状态 session.setAttribute("loginTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); // 登录时间 return "redirect:/index.jsp"; // 登录成功,跳转到主页 } // 登录失败,返回登录页面并传递错误信息 model.addAttribute("loginError", "用户名或密码错误,请重新尝试。"); return "login/login.jsp"; } // 显示注册页面 @GetMapping("/register") public String registerPage() { return "/login/register.jsp"; // 返回注册页面 } // 处理注册请求 @PostMapping("/register") public String register(User user, Model model) { if (userService.register(user)) { return "/login/login.jsp"; // 注册成功,跳转到登录页面 } model.addAttribute("registerError", "用户名已存在"); // 用户名已存在 return "/login/register.jsp"; // 注册失败,返回注册页面 } // 处理退出登录 @GetMapping("/logout") public String logout(HttpSession session) { User user = (User) session.getAttribute("user"); if (user != null) { userService.updateUserStatus(user.getUserId(), "离线"); } session.invalidate(); // 清除session return "redirect:/login/login.jsp"; // 返回登录页面 } } 这是我实现登录注册的配置: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.cxy.Mapper.UserMapper"> <!-- 查询用户 --> <select id="findByUsername" resultType="com.cxy.Pojo.User"> SELECT * FROM users WHERE username = #{username} </select> <!-- 插入新用户 --> <insert id="insertUser" parameterType="com.cxy.Pojo.User"> INSERT INTO users (username, password, role) VALUES (#{username}, #{password}, #{role}) </insert> <!-- 更新在线状态 --> <update id="updateStatus"> UPDATE users SET status = #{status} WHERE user_id = #{user_id} </update> </mapper> application-dao.xml:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置数据源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.cxy.Mapper"/> </bean> </beans> application-service.xml:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 配置组件扫描 --> <context:component-scan base-package="com.cxy.Service"/> </beans> spring-mvc.xml:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.cxy.Controller"/> <mvc:annotation-driven/> <mvc:resources mapping="/css/**" location="/css/" /> </beans> web.xml:<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:application-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Spring DispatcherServlet --> <servlet> <servlet-name>Dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 配置 Spring DispatcherServlet 映射 --> <servlet-mapping> <servlet-name>Dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> index.jsp: <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.util.Date" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html> <html> <head> <title>动物园数字档案管理系统</title> <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/index.css"> </head> <body> <!-- 顶部导航栏 --> <header> <div class="logo"> <img src="<%= request.getContextPath() %>/images/zoo-logo.png" alt="Zoo Logo"> </div> <nav> <ul> <li><a href="${pageContext.request.contextPath}/index.jsp">首页</a></li> <li><a href="${pageContext.request.contextPath}/animal.jsp">动物信息</a></li> <li><a href="${pageContext.request.contextPath}/activities.jsp">活动预约</a></li> <li><a href="${pageContext.request.contextPath}/forum.jsp">用户交流</a></li> <% String username = (String) session.getAttribute("username"); String userRole = (String) session.getAttribute("role"); String userStatus = (String) session.getAttribute("status"); if ("饲养者".equals(userRole)) { out.println("<li><a href='" + request.getContextPath() + "/animal/list'>我的动物</a></li>"); } else if ("管理员".equals(userRole)) { out.println("<li><a href='" + request.getContextPath() + "/animal/list'>所有动物</a></li>"); } if (username == null) { out.println("<li><a href='" + request.getContextPath() + "/login/login.jsp'>登录/注册</a></li>"); } else { out.println("<li><a href='" + request.getContextPath() + "/logout'>退出登录</a></li>"); out.println("<li><span>登录时间: " + session.getAttribute("loginTime") + "</span></li>"); } %> </ul> </nav> </header> <!-- 主要内容 --> <div class="content"> <% if ("游客".equals(userRole)) { %> <div class="animal-search"> <h2>探索动物世界</h2> <input type="text" placeholder="搜索动物..."> <button onclick="window.location.href='${pageContext.request.contextPath}/activities.jsp'">立即预约活动</button> </div> <% } else if ("饲养者".equals(userRole)) { %> <div class="manage-animals"> <h2>饲养者面板</h2> <p>欢迎,<%= username %>!您当前状态:<%= userStatus %></p> </div> <% } else if ("管理员".equals(userRole)) { %> <div class="admin-panel"> <h2>管理员面板</h2> <p>欢迎,<%= username %>!您当前状态:<%= userStatus %></p> </div> <% } else { %> <div class="welcome-message"> <h2>欢迎来到动物园数字档案管理系统</h2> <p>请登录或注册以获取更多功能。</p> <button onclick="window.location.href='${pageContext.request.contextPath}/login/login.jsp'">登录/注册</button> </div> <% } %> </div> <!-- 底部信息栏 --> <footer> <div class="footer-content"> <p>©2023 动物园数字档案管理系统</p> <p>联系我们:info@zoodatabase.com</p> </div> </footer> </body> </html> add_animal.jsp: <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <title>添加动物 - 动物园数字档案管理系统</title> <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/animal_form.css"> </head> <body> <jsp:include page="/header.jsp"/> <div class="container"> <h1>添加新动物</h1> <form action="${pageContext.request.contextPath}/animal/add" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="name">动物名称:</label> <input type="text" id="name" name="name" required> </div> <div class="form-group"> <label for="species">种类:</label> <input type="text" id="species" name="species" required> </div> <div class="form-group"> <label for="gender">性别:</label> <select id="gender" name="gender" required> <option value="">请选择</option> <option value="雄">雄</option> <option value="雌">雌</option> </select> </div> <div class="form-group"> <label for="age">年龄:</label> <input type="number" id="age" name="age" min="0" required> </div> <div class="form-group"> <label for="zone">位置:</label> <input type="text" id="zone" name="zone" required> </div> <div class="form-group"> <label for="photo_url">上传照片:</label> <input type="file" id="photo_url" name="photo_url" multiple> </div> <div class="form-group"> <label for="nature">性格:</label> <input type="text" id="nature" name="nature" required> </div> <div class="form-group"> <label for="favourite">喜好描述:</label> <textarea id="favourite" name="favourite"></textarea> </div> <div class="form-actions"> <button type="submit" class="btn btn-primary">添加动物</button> <a href="${pageContext.request.contextPath}/animal/list" class="btn btn-secondary">取消</a> </div> </form> </div> 注意:查询查的是动物完整的信息(包括图片),添加也要添加动物完整的信息,可以对数据库插入动物图片。这需要对表进行关联。 请根据我的配置和我给出的添加动物页面add_aniaml.jsp,用javaee的ssm整合框架实现饲养者和管理者对动物的增删改查,,以及写出对应的jsp页面:在/animal/目录内,并修改index页面。包括(controller接口,mapper接口,service,serviceimpl和Mapper新配置)。其中饲养者登录时:显示我的动物导航栏,点击进入页面只能对自己添加的动物进行修改数据和删除,也可以在该页面添加新的动物。而管理者登录时:显示所有动物导航栏,点击进入页面,可以对全部动物信息增删改。饲养者和管理者可以对动物所有信息进行写入。
05-29
<%@ 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
发出的红包

打赏作者

蟹道人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值