Representational State Transfer表现层资源状态转移 。它结构清晰、符合标准、易于理解、扩展方便,是目前最流行的一种互联网软件架构
资源(Resources): 网络上的一个实体,或者说是网络上的一个具体存在信息
资源状态/表述: 对于资源在某个特定时刻的表现形式可以用不同的格式描述, 以便资源在客户端-服务器端之间转移(交换)
资源状态转移(State Transfer): 资源在客户端和服务器交互过程中的转移(transfer), 通过转移和操作资源的表述,来间接实现操作资源的目的
REST 是一种将URL地址使用从前到后各个单词使用斜杠分开的风格设计,不使用问号键值对方式携带请求参数,而是将请求参数作为 URL 地址的一部分
操作 | 传统方式 | REST风格 |
---|---|---|
根据id查询操作 | getUserById?id=1 | user/1–>get请求方式 |
保存操作 | saveUser | user–>post请求方式 |
根据id删除操作 | deleteUser?id=1 | user/1–>delete请求方式 |
更新操作 | updateUser | user–>put请求方式 |
由于浏览器只支持发送get和post方式的请求,此时需要使用SpringMVC提供的 HiddenHttpMethodFilter帮助我们将 POST 请求转换为 DELETE 或 PUT 请求
SpringMVC中提供了两个过滤器:CharacterEncodingFilter和HiddenHttpMethodFilter, 必须先注册CharacterEncodingFilter,再注册HiddenHttpMethodFilter
在web.xml中注册HiddenHttpMethodFilter
<filter>
<filter-name>HiddenHttpMethodFilterfilter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
HiddenHttpMethodFilter源码
public class HiddenHttpMethodFilter extends OncePerRequestFilter {
// ALLOWED_METHODS是个List集合,集合中的元素是PUT,DELETE,PATCH
private static final List<String> ALLOWED_METHODS =
Collections.unmodifiableList(Arrays.asList(HttpMethod.PUT.name(),//HttpMethod是枚举类型
HttpMethod.DELETE.name(), HttpMethod.PATCH.name()));
public static final String DEFAULT_METHOD_PARAM = "_method";
private String methodParam = DEFAULT_METHOD_PARAM;
public void setMethodParam(String methodParam) {
Assert.hasText(methodParam, "'methodParam' must not be empty");
this.methodParam = methodParam;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
//接收原生的request
HttpServletRequest requestToUse = request;
if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
//获取当前请求参数的值,this.methodParam的值是"_method"
String paramValue = request.getParameter(this.methodParam);
if (StringUtils.hasLength(paramValue)) {
//ALLOWED_METHODS是个List集合,元素是PUT,DELETE,PATCH
String method = paramValue.toUpperCase(Locale.ENGLISH);
if (ALLOWED_METHODS.contains(method)) {
//重新包装一个请求对象,重写了getMethod方法即改掉了method属性的值
requestToUse = new HttpMethodRequestWrapper(request, method);
}
}
}
//过滤器放行执行下一个过滤器或者Servlet,传递的是我们新包装的requestToUse对象
filterChain.doFilter(requestToUse, response);
}
//对原生的request对象进行包装
private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {
private final String method;
public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
super(request);
this.method = method;
}
@Override
//重写父类的getMethod方法,返回的是当前对象的method属性的值
public String getMethod() {
return this.method;
}
}
}
第一步: 创建maven工程手动添加web模块(直接创建)
第二步: 指定Maven工程的打包方式:war
第三步: 引入依赖: 由于 Maven 的传递性,我们不必将所有需要的包全部配置依赖,而是配置最顶端的依赖,其他靠传递性导入
**第四步: 配置web.xml, 注册SpringMVC的前端控制器DispatcherServlet配置其所能处理的请求的请求路径(告诉前端控制器配置文件的名称和位置) **
<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>CharacterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceResponseEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<filter>
<filter-name>HiddenHttpMethodFilterfilter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<servlet>
<servlet-name>DispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springMVC.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>DispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
第五步: 创建请求控制器(处理具体请求的类)
@Controller
public class EmployeeController {
@Autowired
private EmployeeDao employeeDao;
//编写控制器方法
}
第六步: 创建springMVC的配置文件(Spring的配置文件), 扫描所有组件 , 配置视图解析器和视图控制器
<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.atguigu.rest">context:component-scan>
<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:view-controller path="/" view-name="index">mvc:view-controller>
<mvc:view-controller path="/toAdd" view-name="employee_add">mvc:view-controller>
<mvc:default-servlet-handler />
<mvc:annotation-driven />
beans>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="defaultCharset" value="UTF-8" />
<property name="supportedMediaTypes">
<list>
<value>text/htmlvalue>
<value>application/jsonvalue>
list>
property>
bean>
mvc:message-converters>
mvc:annotation-driven>
准备实体类POJO
public class Employee {
private Integer id;
private String lastName;
private String email;
//1 male, 0 female
private Integer gender;
//get和set方法
public Employee(Integer id, String lastName, String email, Integer gender) {
super();
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
}
public Employee() {
}
}
准备dao实现类模拟连接数据库做增删改查操作
@Repository
public class EmployeeDao {
private static Map<Integer, Employee> employees = null;
static{
employees = new HashMap<Integer, Employee>();
employees.put(1001, new Employee(1001, "E-AA", "[email protected]", 1));
employees.put(1002, new Employee(1002, "E-BB", "[email protected]", 1));
employees.put(1003, new Employee(1003, "E-CC", "[email protected]", 0));
employees.put(1004, new Employee(1004, "E-DD", "[email protected]", 0));
employees.put(1005, new Employee(1005, "E-EE", "[email protected]", 1));
}
private static Integer initId = 1006;
//添加和修改员工信息
public void save(Employee employee){
if(employee.getId() == null){
employee.setId(initId++);
}
employees.put(employee.getId(), employee);
}
//查询所有员工信息
public Collection<Employee> getAll(){
return employees.values();
}
//根据id查询某个员工信息
public Employee get(Integer id){
return employees.get(id);
}
//根据id删除某个员工信息
public void delete(Integer id){
employees.remove(id);
}
}
功能 | URL 地址 | 请求方式 |
---|---|---|
访问首页 | / | GET |
查询全部数据 | /employee | GET |
删除 | /employee/2 | DELETE |
跳转到添加数据页面 | /toAdd | GET |
执行保存 | /employee | POST |
跳转到更新数据页面 | /employee/2 | GET |
执行更新 | /employee | PUT |
在SpringMvc配置文件中配置view-controller标签
<mvc:view-controller path="/" view-name="index"/>
<mvc:annotation-driven />
创建页面index.html
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" >
<title>Titletitle>
head>
<body>
<h1>首页h1>
<a th:href="@{/employee}">访问员工信息a>
body>
html>
查询所有员工的控制器方法
@RequestMapping(value = "/employee", method = RequestMethod.GET)
public String getEmployeeList(Model model){
Collection<Employee> employeeList = employeeDao.getAll();
//选择请求域存放数据
model.addAttribute("employeeList", employeeList);
return "employee_list";
}
创建employee_list.html,动态显示所有员工的信息,并提供了对员工增删改查的操作链接
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Employee Infotitle>
<script type="text/javascript" th:src="@{/static/js/vue.js}">script>
head>
<body>
<table border="1" cellpadding="0" cellspacing="0" style="text-align: center;" id="dataTable">
<tr>
<th colspan="5">Employee Infoth>
tr>
<tr>
<th>idth>
<th>lastNameth>
<th>emailth>
<th>genderth>
<th>options(<a th:href="@{/toAdd}">adda>)th>
tr>
<tr th:each="employee : ${employeeList}">
<td th:text="${employee.id}">td>
<td th:text="${employee.lastName}">td>
<td th:text="${employee.email}">td>
<td th:text="${employee.gender}">td>
<td>
"@{'/employee/'+${employee.id}}"或"@{/employee/}+${employee.id}}"
<a class="deleteA" @click="deleteEmployee" th:href="@{'/employee/'+${employee.id}}">deletea>
<a th:href="@{'/employee/'+${employee.id}}">updatea>
td>
tr>
table>
body>
html>
delete删除的超链接在employee_list.html动态响应的内容中,点击超链接执行事件
DefaultServlet是Tomcat中处理静态资源的(除jsp和servlet) , Tomcat会在服务器下找到这个资源并返回
<mvc:default-servlet-handler />
<mvc:annotation-driven />
<table border="1" cellpadding="0" cellspacing="0" style="text-align: center;" id="dataTable">
<td>
<a class="deleteA" @click="deleteEmployee" th:href="@{'/employee/'+${employee.id}}">deletea>
td>
table>
<form id="delete_form" method="post">
<input type="hidden" name="_method" value="delete"/>
form>
<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>
删除员工的控制器方法
@RequestMapping(value = "/employee/{id}", method = RequestMethod.DELETE)
public String deleteEmployee(@PathVariable("id") Integer id){
employeeDao.delete(id);
//删除成功后重定向到列表页面
return "redirect:/employee";
}
跳转到添加员工信息的页面的链接在employee_list.htm动态响应的内容中
<table border="1" cellpadding="0" cellspacing="0" style="text-align: center;" id="dataTable">
<tr>
<th colspan="5">Employee Infoth>
tr>
<tr>
<th>idth>
<th>lastNameth>
<th>emailth>
<th>genderth>
<th>options(<a th:href="@{/toAdd}">adda>)th>
tr>
table>
在SpringMvc配置文件中配置view-controller标签
<mvc:view-controller path="/toAdd" view-name="employee_add">mvc:view-controller>
<mvc:annotation-driven />
创建employee_add.html保存添加员工的信息并发起POST请求
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Add Employeetitle>
head>
<body>
<form th:action="@{/employee}" method="post">
lastName:<input type="text" name="lastName"><br>
email:<input type="text" name="email"><br>
gender:<input type="radio" name="gender" value="1">male
<input type="radio" name="gender" value="0">female<br>
<input type="submit" value="add"><br>
form>
body>
html>
保存要添加的员工信息的控制器方法
@RequestMapping(value = "/employee", method = RequestMethod.POST)
public String addEmployee(Employee employee){
employeeDao.save(employee);
//重定向到员工列表页面
return "redirect:/employee";
}
跳转到更新页面的的超链接在employee_list.html动态响应的内容中
<table border="1" cellpadding="0" cellspacing="0" style="text-align: center;" id="dataTable">
<td>
<a th:href="@{'/employee/'+${employee.id}}">updatea>
td>
table>
处理跳转到更新员工信息页面请求的控制器方法
@RequestMapping(value = "/employee/{id}", method = RequestMethod.GET)
public String getEmployeeById(@PathVariable("id") Integer id, Model model){
//先查询要修改的员工信息,存放到请求域中
Employee employee = employeeDao.get(id);
model.addAttribute("employee", employee);
return "employee_update";
}
创建employee_update.html, 页面上有要修改员工的信息(id隐藏起来不显示)
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Update Employeetitle>
head>
<body>
<form th:action="@{/employee}" method="post">
<input type="hidden" name="_method" value="put">
<input type="hidden" name="id" th:value="${employee.id}">
lastName:<input type="text" name="lastName" th:value="${employee.lastName}"><br>
email:<input type="text" name="email" th:value="${employee.email}"><br>
gender:<input type="radio" name="gender" value="1" th:field="${employee.gender}">male
<input type="radio" name="gender" value="0" th:field="${employee.gender}">female<br>
<input type="submit" value="update"><br>
form>
body>
html>
保存修改后员工信息的控制器方法
@RequestMapping(value = "/employee", method = RequestMethod.PUT)
public String updateEmployee(Employee employee){
employeeDao.save(employee);
//重定向到列表页面
return "redirect:/employee";
}