使用SpringMVC实现对一个表的增删改查
视频课程里面已经教了增删查三个功能,主要修改功能是自己实现的。
思路:增加一个修改数据的按钮,点击时将这一条数据的id作为参数,查询到数据库里对应的数据,返回到专门的修改页面上,修改页面可以复制自增加页面来使用。
点击更新以后就执行更新方法,再重定向回查询所有用户的主页面。
中间遇到的问题是,使用request传递不了查询出来的单个Teacher对象到修改页面,经过百度以后,使用request.getSession().setAttribute解决:1、如果你是在同一个服务器(容器)里做的转向工作。那么可以这样
把request.setAttribute(“cha”, cha);改成request.getSession().setAttribute(“cha”, cha);
然后<%Object a = (Object)request.getSession().getAttribute(“cha”);%>其他不变。
参考链接:https://blog.csdn.net/qq_33551891/article/details/88988181
项目创建步骤1,先在resources文件夹下配置好SpringMVC,Spring,Mybaits的相关配置文件:
db.properties
jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8&useSSL=false jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.username=root jdbc.password=zengyu1234
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <package name="com.xzit.entity"/> </typeAliases> <mappers> <package name="com.xzit.mapper"/> </mappers> </configuration>
springmvc.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" xmlns:mvc="http://www.alibaba.com/schema/stat" 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.alibaba.com/schema/stat http://www.alibaba.com/schema/stat.xsd"> <!--自动扫描--> <context:component-scan base-package="com.xzit"></context:component-scan> <!--处理器映射器和适配器--> <mvc:annotation-driven></mvc:annotation-driven> </beans>
applicationContext.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 https://www.springframework.org/schema/context/spring-context.xsd"> <!--对应db.properties文件--> <context:property-placeholder location="classpath:db.properties"></context:property-placeholder> <!--数据源--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!--配置SqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:SqlMapConfig.xml"></property> </bean> <!--对Mapper的扫描--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> <!--配置Mapper文件的基准包--> <property name="basePackage" value="com.xzit.mapper"></property> </bean> </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"> <!--spring配置--> <!--配置加载ApplicationContext--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--配置spring文件的地址--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!--springmvc配置--> <!--配置前端控制器--> <servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--配置初始化参数,指定springmvc配置文件的位置--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>mvc</servlet-name> <!--过滤除jsp以外的资源--> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>springmvc_project</artifactId> <groupId>org.example</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>com.xzit</groupId> <artifactId>day7_job</artifactId> <packaging>war</packaging> <name>day7_job Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!--spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.15</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.3.15</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.15</version> </dependency> <!--druid数据源--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.8</version> </dependency> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.28</version> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.9</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.7</version> </dependency> <!--servlet api--> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <!--jsp api--> <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> <scope>provided</scope> </dependency> <!--引用json格式依赖--> <!-- https://mvnrepository.com/artifact/javax.annotation/jsr250-api --> <dependency> <groupId>javax.annotation</groupId> <artifactId>jsr250-api</artifactId> <version>1.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.13.2</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.13.2</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.2</version> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build> </project>
项目创建步骤2,创建好实体类,Mapper和service类,以及解决中文乱码问题的过滤器类:
package com.xzit.entity; import lombok.Data; import lombok.experimental.Accessors; @Data @Accessors(chain = true) public class Teacher { private int id; private String name; private String addr; private int age; private String job; private int sal; }
package com.xzit.mapper; import com.xzit.entity.Teacher; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface TeacherMapper { /*增加老师的方法*/ @Insert("insert into teacher values(null,#{name},#{addr},#{age},#{job},#{sal})") void save(Teacher teacher); /*删除老师的方法*/ @Delete("delete from teacher where id=#{id}") void delete(int id); /*修改老师的方法*/ @Update("update teacher t set t.name=#{name},t.addr=#{addr},t.age=#{age},t.job=#{job},t.sal=#{sal} where t.id=#{id}") void update(Teacher teacher); /*查询老师的方法*/ @Select("select * from teacher") List<Teacher> selectList(); /*根据id查询老师的方法*/ @Select("select * from teacher where id=#{id}") Teacher selectTeacher(int id); }
package com.xzit.service; import com.xzit.entity.Teacher; import java.util.List; public interface TeacherService { void save(Teacher teacher); void delete(int id); void update(Teacher teacher); List<Teacher> selectList(); Teacher selectTeacher(int id); }
package com.xzit.service; import com.xzit.entity.Teacher; import com.xzit.mapper.TeacherMapper; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; @Service public class TeacherServiceImpl implements TeacherService { @Resource private TeacherMapper teacherMapper; @Override public void save(Teacher teacher) { teacherMapper.save(teacher); } @Override public void delete(int id) { teacherMapper.delete(id); } @Override public void update(Teacher teacher) { teacherMapper.update(teacher); } @Override public List<Teacher> selectList() { return teacherMapper.selectList(); } @Override public Teacher selectTeacher(int id) { return teacherMapper.selectTeacher(id); } }
package com.xzit.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.IOException; /** * 配置过滤器解决servlet请求传输的中文乱码的问题 */ @WebFilter("/*") public class EncodingFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); filterChain.doFilter(servletRequest,servletResponse); } }
项目创建步骤3,写完Controller类和jsp页面
package com.xzit.controller; import com.xzit.entity.Teacher; import com.xzit.service.TeacherService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.servlet.*; import javax.servlet.http.*; import java.io.BufferedReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.Principal; import java.util.*; @Controller public class TeacherController { @Resource private TeacherService teacherService; /*增*/ @PostMapping("save") public String save(Teacher teacher){ teacherService.save(teacher); //重定向 return "redirect:select"; } /*删*/ @RequestMapping("delete/{id}") public String delete(@PathVariable int id){ teacherService.delete(id); return "redirect:/select"; } /*改*/ @PostMapping("update") public String update(Teacher teacher){ teacherService.update(teacher); //重定向 return "redirect:select"; } /*查*/ @GetMapping("select") public String select(HttpServletRequest request){ List<Teacher> list=teacherService.selectList(); request.setAttribute("list",list); return "list.jsp"; } /*按照id查询老师到修改页面*/ @GetMapping ("updateId/{id}") public String selectTeacher(@PathVariable("id") Integer id,HttpServletRequest request){ Teacher teacher=teacherService.selectTeacher(id); request.getSession().setAttribute("teacher",teacher); return "redirect:/update.jsp"; } }
<%-- Created by IntelliJ IDEA. User: zengy Date: 2022/7/16 Time: 22:37 To change this template use File | Settings | File Templates. --%> <%@ page import="java.util.List" %> <%@ page import="com.xzit.entity.Teacher" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <style> table,td{ border: 1px solid black; border-collapse: collapse; } table{ margin:0 auto; text-align: center; width: 700px; } </style> </head> <body> <table> <tr> <td>序号</td> <td>姓名</td> <td>地址</td> <td>年龄</td> <td>职位</td> <td>工资</td> <td>操作</td> </tr> <%List<Teacher> list= (List<Teacher>) request.getAttribute("list"); int x=1; for (Teacher teacher:list){%> <tr> <td><%=x++%></td> <td><%=teacher.getName()%></td> <td><%=teacher.getAddr()%></td> <td><%=teacher.getAge()%></td> <td><%=teacher.getJob()%></td> <td><%=teacher.getSal()%></td> <td><a href="javascript:;" onclick="doDel(<%=teacher.getId()%>)">删除数据</a></td> <td><a href="javascript:;" onclick="doPost(<%=teacher.getId()%>)">修改数据</a></td> </tr> <%}%> </table> <script> function doDel(id){ if (confirm("确定删除吗?")) location="delete/"+id } function doPost(id){ /*alert(id)*/ location="updateId/"+id } </script> </body> </html>
<%-- Created by IntelliJ IDEA. User: zengy Date: 2022/7/16 Time: 23:38 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="save" method="post"> <div>姓名:<input type="text" name="name"></div> <div>地址:<input type="text" name="addr"></div> <div>年龄:<input type="number" name="age"></div> <div>职位:<input type="text" name="job"></div> <div>工资:<input type="number" name="sal"></div> <div> <button type="submit">提交</button> </div> </form> </body> </html>
<%@ page import="com.xzit.entity.Teacher" %><%-- Created by IntelliJ IDEA. User: zengy Date: 2022/7/16 Time: 23:38 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>更新老师</title> </head> <body> <%Teacher teacher = (Teacher) request.getSession().getAttribute("teacher"); %> <form action="update" method="post"> <div>姓名:<input type="text" name="id" value="<%=teacher.getId()%>"></div> <div>姓名:<input type="text" name="name" value="<%=teacher.getName()%>"></div> <div>地址:<input type="text" name="addr" value="<%=teacher.getAddr()%>"></div> <div>年龄:<input type="number" name="age" value="<%=teacher.getAge()%>"></div> <div>职位:<input type="text" name="job" value="<%=teacher.getJob()%>"></div> <div>工资:<input type="number" name="sal" value="<%=teacher.getSal()%>"></div> <div> <button type="submit">更新</button> </div> </form> </body> </html>