1、ContextLoaderListener
Spring提供了监听器
ContextLoaderListener
,实现
ServletContextListener
接口,可监听 ServletContext的状态,在
web
服务器的启动,读取
Spring
的配置文件,创建
Spring
的
IOC
容器。
web 应用中必须在web.xml
中配置:
<listener>
<!--
配置Spring的监听器,在服务器启动时加载Spring的配置文件
Spring配置文件默认位置和名称:/WEB-INF/applicationContext.xml
可通过上下文参数自定义Spring配置文件的位置和名称
-->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
代码示例:
web.xml:
<servlet>
<servlet-name>DispatcherServlet</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>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<!--
配置Spring的监听器,在服务器启动时加载Spring的配置文件
Spring配置文件默认位置和名称:/WEB-INF/applicationContext.xml
可通过上下文参数自定义Spring配置文件的位置和名称
-->
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
spring.xml:
<context:component-scan base-package="com.chenyixin.ssm.service"/>
springmvc.xml:
<!--开启组件扫描-->
<context:component-scan base-package="com.chenyixin.ssm.controller"/>
<!-- 配置Thymeleaf视图解析器 -->
<bean id="viewResolver"
class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="order" value="1"/>
<property name="characterEncoding" value="UTF-8"/>
<property name="templateEngine">
<bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver">
<bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<!-- 视图前缀 -->
<property name="prefix" value="/WEB-INF/templates/"/>
<!-- 视图后缀 -->
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8"/>
</bean>
</property>
</bean>
</property>
</bean>
<!-- 开启mvc注解驱动 -->
<mvc:annotation-driven/>
<!-- 配置视图控制器 -->
<mvc:view-controller path="/" view-name="index"/>
创建 Service 层(除注解外,无代码内容)
创建 Controller 层
@Controller
public class HelloController {
@Autowired
private HelloService helloService;
}
index.html:
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>index.html</h1>
</body>
结果:运行服务器,正常运行
若将监听器注释掉,则服务器运行报错:
<!--<listener>-->
<!-- <!–-->
<!-- 配置Spring的监听器,在服务器启动时加载Spring的配置文件-->
<!-- Spring配置文件默认位置和名称:/WEB-INF/applicationContext.xml-->
<!-- 可通过上下文参数自定义Spring配置文件的位置和名称-->
<!-- –>-->
<!-- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>-->
<!--</listener>-->
<!--<context-param>-->
<!-- <param-name>contextConfigLocation</param-name>-->
<!-- <param-value>classpath:spring.xml</param-value>-->
<!--</context-param>-->
2、准备工作
① 创建Maven Module
② 导入依赖
<properties>
<spring.version>5.3.1</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<!--springmvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring 持久化层支持jar包 -->
<!--
Spring 在执行持久化层操作、与持久化层技术进行整合过程中,
需要使用orm、jdbc、tx三个 jar包
-->
<!-- 导入 orm 包就可以通过 Maven 的依赖传递性把其他两个也导入 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.3.1</version>
</dependency>
<!-- Mybatis核心 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!--mybatis和spring的整合包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<!-- log4j日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- ServletAPI -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- Spring5和Thymeleaf整合包 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
</dependencies>
③ 创建表
CREATE TABLE `t_emp` (
`emp_id` int(11) NOT NULL AUTO_INCREMENT,
`emp_name` varchar(20) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`sex` char(1) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
PRIMARY KEY (`emp_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
INSERT INTO t_emp VALUES
(1001,'admin',20,'男','admin@qq.com'),
(NULL,'zhangsan',21,'女','zhangsan@qq.com'),
(NULL,'lisi',21,'女','lisi@qq.com'),
(NULL,'wangwu',21,'男','wangwu@qq.com'),
(NULL,'zaoliu',21,'男','zaoliu@qq.com'),
(NULL,'tianqi',22,'女','tianqi@qq.com'),
(NULL,'张三',21,'女','zhangsan@qq.com'),
(NULL,'李四',21,'女','lisi@qq.com'),
(NULL,'王五',21,'男','wangwu@qq.com'),
(NULL,'赵六',21,'男','zaoliu@qq.com'),
(NULL,'田七',22,'女','tianqi@qq.com'),
(NULL,'xioaming',22,'男','xioaming@qq.com'),
(NULL,'xiaohua',22,'男','xiaohua@qq.com'),
(NULL,'xiaozhang',22,'男','xiaozhang@qq.com'),
(NULL,'xiaowang',22,'男','xiaowang@qq.com'),
(NULL,'xiaofang',22,'女','xiaofang@qq.com'),
(NULL,'小明',22,'男','xioaming@qq.com'),
(NULL,'小华',22,'男','xiaohua@qq.com'),
(NULL,'小张',22,'男','xiaozhang@qq.com'),
(NULL,'小王',22,'男','xiaowang@qq.com'),
(NULL,'小芳',22,'女','xiaofang@qq.com')
④ 创建实体类Employee
package com.chenyixin.ssm.pojo;
public class Employee {
private Integer empId;
private String empName;
private Integer age;
private String sex;
private String email;
public Employee(Integer empId, String empName, Integer age, String sex, String email) {
this.empId = empId;
this.empName = empName;
this.age = age;
this.sex = sex;
this.email = email;
}
public Employee() {
}
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Employee{" +
"empId=" + empId +
", empName='" + empName + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", email='" + email + '\'' +
'}';
}
}
3、配置 xml 文件
3.1、配置 web.xml 文件
<!-- 配置Spring的编码过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置处理请求方式PUT和DELETE的过滤器 -->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置SpringMVC的前端控制器 -->
<servlet>
<servlet-name>DispatcherServlet</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>
<!-- 将 DispatcherServlet 的初始化时间提前到服务器启动时 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置Spring的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 设置Spring的配置文件的位置和名称 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
3.2、
创建SpringMVC的配置文件并配置
<!--开启组件扫描-->
<context:component-scan base-package="com.chenyixin.ssm.controller"/>
<!-- 配置Thymeleaf视图解析器 -->
<bean id="viewResolver"
class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="order" value="1"/>
<property name="characterEncoding" value="UTF-8"/>
<property name="templateEngine">
<bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver">
<bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<!-- 视图前缀 -->
<property name="prefix" value="/WEB-INF/templates/"/>
<!-- 视图后缀 -->
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8"/>
</bean>
</property>
</bean>
</property>
</bean>
<!-- 配置默认的servlet处理静态资源 -->
<mvc:default-servlet-handler/>
<!-- 开启 mvc 注解驱动 -->
<mvc:annotation-driven/>
<!-- 配置访问首页的视图控制 -->
<mvc:view-controller path="/" view-name="index"/>
3.3、
创建Spring的配置文件并配置
<!-- 组件扫描(除控制层) -->
<context:component-scan base-package="com.chenyixin.ssm">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 引入jdbc.properties -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置Druid数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--
开始事务驱动
将使用注解 @Transaction 标识的方法或类中的多有方法进行事务管理
-->
<tx:annotation-driven transaction-manager="transactionManager"/>
4、
搭建MyBatis环境
① 创建属性文件jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
jdbc.username=root
jdbc.password=root
② 在
Spring 的配置文件中添加 MyBatis 的配置
<!-- 配置用于创建SqlSessionFactory的工厂bean -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 设置MyBatis配置文件的路径(可以不设置) -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 设置数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 设置类型别名所对应的包 -->
<property name="typeAliasesPackage" value="com.chenyixin.ssm.pojo"/>
<!--
设置映射文件的路径
若映射文件所在路径和mapper接口所在路径一致,则不需要设置
(前提是设置了 mapper 接口的扫描配置 的 bean)
-->
<!--<property name="mapperLocations" value="mappers/*.xml"/>-->
</bean>
<!--
配置 mapper 接口的扫描配置
由mybatis-spring提供,可以将指定包下所有的mapper接口创建动态代理
并将这些动态代理作为IOC容器的bean管理
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.chenyixin.ssm.mapper"/>
</bean>
③ 创建MyBatis的核心配置文件mybatis-config.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>
<!--
MyBatis核心配置文件中,标签的顺序:
properties?,settings?,typeAliases?,typeHandlers?, objectFactory?,objectWrapperFactory?,
reflectorFactory?, plugins?,environments?,databaseIdProvider?,mappers?
-->
<!-- 将下滑线映射为驼峰 -->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<plugins>
<!--配置分页插件-->
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
</configuration>
④
创建Mapper接口和映射文件
EmployeeMapper 接口:
public interface EmployeeMapper {
}
EmployeeMapper.xml 映射文件:
<?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.chenyixin.ssm.mapper.EmployeeMapper">
</mapper>
⑤ 创建日志文件log4j.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n"/>
</layout>
</appender>
<logger name="java.sql">
<level value="debug"/>
</logger>
<logger name="org.apache.ibatis">
<level value="info"/>
</logger>
<root>
<level value="debug"/>
<appender-ref ref="STDOUT"/>
</root>
</log4j:configuration>
5、功能实现
5.1、功能清单
5.2、访问首页
创建 index.html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<h1>index.html</h1>
<a th:href="@{/employee}">员工信息列表</a>
</body>
</html>
5.3、查询全部数据(含分页功能)
① Java 代码
EmployeeController :
@Controller
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@GetMapping("/employee/page/{pageNum}")
public String getAllEmployee(Model model,@PathVariable("pageNum") Integer pageNum) {
PageInfo<Employee> page = employeeService.getAllEmployee(pageNum);
model.addAttribute("page", page);
return "employee_list";
}
}
EmployeeService :
public interface EmployeeService {
/**
* 查询所有员工信息
* @return List<Employee>
*/
PageInfo<Employee> getAllEmployee(Integer pageNum);
}
EmployeeServiceImpl
@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeMapper employeeMapper;
@Override
public PageInfo<Employee> getAllEmployee(Integer pageNum) {
// 开启分页功能,并传入 当前页面,和每页显示的条数
PageHelper.startPage(pageNum,4);
List<Employee> list = employeeMapper.selectAllEmployee();
// 创建 PageInfo ,传入 list 和 导航分页的页码数
return new PageInfo<>(list, 5);
}
}
EmployeeMapper
public interface EmployeeMapper {
/**
* 查询所有员工信息
* @return List<Employee>
*/
List<Employee> selectAllEmployee();
}
② Mybaits 代码
<mapper namespace="com.chenyixin.ssm.mapper.EmployeeMapper">
<!--List<Employee> selectAllEmployee();-->
<select id="selectAllEmployee" resultType="employee">
select * from t_emp
</select>
</mapper>
③ employee_list.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<link rel="stylesheet" th:href="@{/static/css/index_work.css}">
<head>
<meta charset="UTF-8">
<title>员工信息表</title>
</head>
<body>
<table>
<tr>
<th colspan="6">员工信息</th>
</tr>
<tr>
<th>流水号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>邮箱</th>
<th>操作</th>
</tr>
<tr th:each="employee , status: ${page.list}">
<td th:text="${status.count}"></td>
<td th:text="${employee.empName}"></td>
<td th:text="${employee.age}"></td>
<td th:text="${employee.sex}"></td>
<td th:text="${employee.email}"></td>
<td>
<a>删除</a>
<a>修改</a>
</td>
</tr>
<tr>
<td colspan="6">
<span th:if="${page.hasPreviousPage}">
<a th:href="@{/employee/page/1}">首页</a>
<a th:href="@{'/employee/page/'+${page.prePage}}">上一页</a>
</span>
<span th:each="num : ${page.navigatepageNums}">
<a th:if="${page.pageNum == num}" style="color: orangered" th:href="@{'/employee/page/'+${num}}" th:text="'【'+${num}+'】'"></a>
<a th:if="${page.pageNum != num}" th:href="@{'/employee/page/'+${num}}" th:text="${num}"></a>
</span>
<span th:if="${page.hasNextPage }">
<a th:href="@{'/employee/page/'+${page.nextPage}}">下一页</a>
<a th:href="@{'/employee/page/'+${page.pages}}">末页</a>
</span>
</td>
</tr>
</table>
</body>
</html>
5.4 删除功能
① 修改employee_list.html,并添加事件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<link rel="stylesheet" th:href="@{/static/css/index_work.css}">
<head>
<meta charset="UTF-8">
<title>员工信息表</title>
</head>
<body>
<table id="dataTable">
<tr>
<th colspan="6">员工信息</th>
</tr>
<tr>
<th>流水号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>邮箱</th>
<th>操作</th>
</tr>
<tr th:each="employee , status: ${page.list}">
<td th:text="${status.count}"></td>
<td th:text="${employee.empName}"></td>
<td th:text="${employee.age}"></td>
<td th:text="${employee.sex}"></td>
<td th:text="${employee.email}"></td>
<td>
<a @click="deleteEmployee" th:href="@{'/employee/'+${employee.empId}}">删除</a>
<a>修改</a>
</td>
</tr>
<tr>
<td colspan="6">
<span th:if="${page.hasPreviousPage}">
<a th:href="@{/employee/page/1}">首页</a>
<a th:href="@{'/employee/page/'+${page.prePage}}">上一页</a>
</span>
<span th:each="num : ${page.navigatepageNums}">
<a th:if="${page.pageNum == num}" style="color: orangered" th:href="@{'/employee/page/'+${num}}"
th:text="'['+${num}+'] '"></a>
<a th:if="${page.pageNum != num}" th:href="@{'/employee/page/'+${num}}" th:text="${num+' '}"></a>
</span>
<span th:if="${page.hasNextPage }">
<a th:href="@{'/employee/page/'+${page.nextPage}}">下一页</a>
<a th:href="@{'/employee/page/'+${page.pages}}">末页</a>
</span>
</td>
<td>
<!-- 作用:通过超链接控制表单的提交,将post请求转换为delete请求 -->
<form id="delete_form" method="post">
<!-- HiddenHttpMethodFilter要求:必须传输_method请求参数,并且值为最终的请求方式 -->
<input type="hidden" name="_method" value="delete"/>
</form>
</td>
</tr>
</table>
<!-- 引入vue -->
<script type="text/javascript" th:src="@{/static/js/vue.js}"></script>
<script type="text/javascript">
var vue = new Vue({
el: "#dataTable",
methods: {
// event 表示当前事件
deleteEmployee: function (event) {
// 通过 id 获取表单标签
var delete_form = document.getElementById("delete_form");
// 将触发事件的超链接的 href 属性为表单的 action 属性赋值
delete_form.action = event.target.href;
// 提交表单
delete_form.submit();
// 阻止超链接的默认跳转行为
event.preventDefault();
}
}
});
</script>
</body>
</html>
②
控制器方法
@DeleteMapping("/employee/{id}")
public String deleteEmployeeById(@PathVariable Integer id, @RequestHeader("Referer") String referer) {
employeeService.deleteEmployeeById(id);
return "redirect:" + referer;
}
5.5 添加员工信息功能
① 修改
employee_list.html
作用:跳转到添加数据页面
②
创建employee_add.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<link rel="stylesheet" th:href="@{/static/css/index_work.css}">
<head>
<meta charset="UTF-8">
<title>添加员工信息</title>
</head>
<body>
<form th:action="@{/employee}" method="post">
<table id="dataTable">
<tr>
<th colspan="2">添加员工信息</th>
</tr>
<tr>
<td>姓名</td>
<td>
<input type="text" name="empName"/>
</td>
</tr>
<tr>
<td>年龄</td>
<td>
<input type="text" name="age" />
</td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="text" name="sex">
</td>
</tr>
<tr>
<td>邮箱</td>
<td>
<input type="text" name="email" >
</td>
</tr>
<tr>
<th colspan="2">
<input type="submit" value="添加">
<input type="reset" value="重置">
</th>
</tr>
</table>
</form>
</body>
</html>
③ 控制器方法
@RequestMapping("/employee/to/add")
public String toADD(@RequestHeader("Referer") String referer) {
this.referer = referer;
return "employee_add";
}
@PostMapping("/employee")
public String addEmployee(Employee employee) {
employeeService.addEmployee(employee);
return "redirect:"+referer;
}
④ 添加方法
EmployeeService 接口:
/**
* 添加用户信息
* @param employee
*/
void addEmployee(Employee employee);
EmployeeServiceImpl 实现类:
@Override
public void addEmployee(Employee employee) {
employeeMapper.insertEmployee(employee);
}
EmployeeMapper 接口:
/**
* 添加用户信息
* @param employee
*/
void insertEmployee(Employee employee);
EmployeeMapper.xml 配置文件:
<!--void insertEmployee(Employee employee);-->
<insert id="insertEmployee">
insert into t_emp values(null,#{empName},#{age},#{sex},#{email})
</insert>
5.6 更新员工数据功能
① 修改超链接
②
创建employee_update.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<link rel="stylesheet" th:href="@{/static/css/index_work.css}">
<head>
<meta charset="UTF-8">
<title>修改员工信息</title>
</head>
<body>
<form th:action="@{/employee}" method="post">
<input type="hidden" name="_method" value="put">
<input type="hidden" name="empId" th:value="${employee.empId}">
<table id="dataTable">
<tr>
<th colspan="2">修改员工信息</th>
</tr>
<tr>
<td>姓名</td>
<td>
<input type="text" name="empName" th:value="${employee.empName}"/>
</td>
</tr>
<tr>
<td>年龄</td>
<td>
<input type="text" name="age" th:value="${employee.age}"/>
</td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio" name="sex" value="男" th:field="${employee.sex}">男
<input type="radio" name="sex" value="女" th:field="${employee.sex}">女
</td>
</tr>
<tr>
<td>邮箱</td>
<td>
<input type="text" name="email" th:value="${employee.email}">
</td>
</tr>
<tr>
<th colspan="2">
<input type="submit" value="修改">
<input type="reset" value="重置">
</th>
</tr>
</table>
</form>
</body>
</html>
③
控制器方法
@GetMapping("/employee/{id}")
public String toUpdate(@RequestHeader("Referer") String referer, @PathVariable Integer id, Model model) {
Employee employee = employeeService.getEmployeeById(id);
model.addAttribute("employee", employee);
this.referer = referer;
return "employee_update";
}
@PutMapping("/employee")
public String UpdateEmployee(Employee employee) {
employeeService.updateEmployee(employee);
return "redirect:" + referer;
}
④ 修改方法
EmployeeService 接口:
/**
* 根据 id 查询员工信息
* @param id
*/
Employee getEmployeeById(Integer id);
/**
* 修改用户信息
* @param employee
*/
void updateEmployee(Employee employee);
EmployeeServiceImpl 实现类:
@Override
public Employee getEmployeeById(Integer id) {
return employeeMapper.selectEmployeeById(id);
}
@Override
public void updateEmployee(Employee employee) {
employeeMapper.updateEmployee(employee);
}
EmployeeMapper 接口:
/**
* 根据 id 查询员工信息
* @param id
*/
Employee selectEmployeeById(Integer id);
/**
* 修改用户信息
* @param employee
*/
void updateEmployee(Employee employee);
EmployeeMapper.xml 配置文件:
<!--void selectEmployeeById(Integer id);-->
<select id="selectEmployeeById" resultType="employee">
select *
from t_emp
where emp_id = #{id}
</select>
<!--void updateEmployee(Employee employee);-->
<update id="updateEmployee">
update t_emp
set emp_name = #{empName},
age = #{age},
sex = #{sex},
email = #{email}
where emp_id = #{empId}
</update>