REST:Representational State Transfer,表现层资源状态转移。
资源是一种看待服务器的方式,即,将服务器看作是由很多离散的资源组成。每个资源是服务器上一个可命名的抽象概念。因为资源是一个抽象的概念,所以它不仅仅能代表服务器文件系统中的一个文件、数据库中的一张表等等具体的东西,可以将资源设计的要多抽象有多抽象,只要想象力允许而且客户端应用开发者能够理解。与面向对象设计类似,资源是以名词为核心来组织的,首先关注的是名词。一个资源可以由一个或多个URL来标识。URL既是资源的名称,也是资源在Web上的地址。对某个资源感兴趣的客户端应用,可以通过资源的URL与其进行交互。
资源的表述是一段对于资源在某个特定时刻的状态的描述。可以在客户端-服务器端之间转移(交换)。资源的表述可以有多种格式,例如HTML/XML/JSON/纯文本/图片/视频/音频等等。资源的表述格式可以通过协商机制来确定。请求-响应方向的表述通常使用不同的格式。
状态转移说的是:在客户端和服务器端之间转移(transfer)代表资源状态的表述。通过转移和操作资源的表述,来间接实现操作资源的目的。
具体说,就是HTTP协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。
它们分别对应四种基本操作:GET用来获取资源,POST用来新建资源,PUT用来更新资源,DELETE用来删除资
源。
REST风格提倡URL地址使用统一的风格设计,从前到后各个单词使用斜杠分开,不使用问号键值对方式携带请求
参数,而是将要发送给服务器的数据作为URL地址的一部分,以保证整体风格的一致性。
操作 | 传统方式 | REST风格 |
---|---|---|
查询操作 | getUserById?id=1 | user/1–>get请求方式 |
保存操作 | saveUser | user–>post请求方式 |
删除操作 | deleteUser?id=1 | user/1–>delete请求方式 |
更新操作 | updateUser | user–>put请求方式 |
前端:
<a th:href="@{/user}">查询所有用户a><br/>
<a th:href="@{/user/1}">根据id查询用户a><br/>
<form th:action="@{/user}" method="post">
<input name="username" type="text" value="admin">
<input name="password" type="password" value="123456">
<input type="submit" value="添加用户"/>
form><br/>
后端:
/*
/user/1-->get 根据id查找user
/users-->get 查询所有用户信息
/user/1-->DELETE 根据id删除用户信息
/user-->PUT 修改用户信息
/user-->POST 新增用户信息
*/
@PostMapping("/user")
public String addUser(String username,String password) {
System.out.println("username:"+username+",password:"+password);
System.out.println("添加用户");
return "success";
}
@GetMapping("/user")
public String queryUserList() {
System.out.println("查询所有用户");
return "success";
}
@GetMapping("/user/{id}")
public String queryUserById(@PathVariable("id") String id) {
System.out.println("查询id为"+id+"的用户");
return "success";
}
需要在web.xml中添加一个过滤器HiddenHttpMethodFilter,其核心代码如下:
使用时必须满足两个条件:
1、必须为post请求
2、必须包含隐藏域_methed,其value对应
PUT、DELETE、PATCH
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
HttpServletRequest requestToUse = request;
if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
String paramValue = request.getParameter(this.methodParam);
if (StringUtils.hasLength(paramValue)) {
String method = paramValue.toUpperCase(Locale.ENGLISH);
if (ALLOWED_METHODS.contains(method)) {
requestToUse = new HttpMethodRequestWrapper(request, method);
}
}
}
filterChain.doFilter(requestToUse, response);
}
web.xml配置:
<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>
前端:
<form th:action="@{/user}" method="post">
<input type="hidden" name="_method" value="PUT">
<input type="text" name="username" value="abc">
<input type="text" name="password" value="123456">
<input type="submit" value="修改用户"/>
form>
<br/>
<form th:action="@{/user/1}" method="post">
<input type="hidden" name="_method" value="delete">
<input type="submit" value="删除用户"/>
form>
<br/>
后端:
@PutMapping("/user")
public String alterUser(String username,String password) {
System.out.println("username:"+username+",password:"+password);
System.out.println("修改用户");
return "success";
}
@DeleteMapping("/user/{id}")
public String deleteUser(@PathVariable("id") String id) {
System.out.println("删除id为"+id+"的用户");
return "success";
}
<table id="employeeTable">
<tr th:colspan="5">
<th>员工信息表th>
tr>
<tr>
<th>idth>
<th>lastNameth>
<th>emailth>
<th>genderth>
<th><a th:href="@{/toAddEmp}">addEmpa>th>
tr>
<tr th:each="emp:${empList}">
<td th:text="${emp.id}">td>
<td th:text="${emp.lastName}">td>
<td th:text="${emp.email}">td>
<td th:text="${emp.gender}">td>
<td><a th:href="@{'/employee/'+${emp.id}}">updatea>td>
<td><a @click="deleteEmployee" th:href="@{'/employee/'+${emp.id}}">deletea>td>
tr>
table>
<tr th:each="emp:${empList}">
<td th:text="${emp.id}">td>
<td th:text="${emp.lastName}">td>
<td th:text="${emp.email}">td>
<td th:text="${emp.gender}">td>
<td><a th:href="@{'/employee/'+${emp.id}}">updatea>td>
<td><a @click="deleteEmployee" th:href="@{'/employee/'+${emp.id}}">deletea>td>
tr>
table>
<form method="post" id="deleteEmployeeForm">
<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: "#employeeTable",
methods: {
deleteEmployee: function (event) {
//获取form表单
var deleteEmployeeForm = document.getElementById("deleteEmployeeForm");
//将delete表单的href内容给form表单的action赋值
deleteEmployeeForm.action = event.target.href;
//提交表单
deleteEmployeeForm.submit();
//取消默认行为
event.preventDefault();
}
}
});
script>
package com.atguigu.controller;
import com.atguigu.bean.Employee;
import com.atguigu.dao.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import java.util.Collection;
@Controller
public class EmployeeController {
@Autowired
EmployeeDao employeeDao;
@RequestMapping(value = "/employee", method = RequestMethod.GET)
public ModelAndView queryEmployeeList() {
ModelAndView modelAndView = new ModelAndView();
Collection<Employee> empList = employeeDao.getAll();
modelAndView.addObject("empList", empList);
modelAndView.setViewName("emp_list");
return modelAndView;
}
@RequestMapping(value = "/employee/{id}", method = RequestMethod.GET)
public ModelAndView getEmployeeById(@PathVariable("id") int id) {
Employee employee = employeeDao.get(id);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("update_emp");
modelAndView.addObject("employee", employee);
return modelAndView;
}
@RequestMapping(value = "/employee/{id}", method = RequestMethod.POST)
public String deleteEmployee(@PathVariable("id") int id) {
employeeDao.delete(id);
return "redirect:/employee";
}
@RequestMapping("/toAddEmp")
public String toAddEmp() {
return "add_emp";
}
@RequestMapping("/addEmp")
public String addEmp(Employee employee) {
employeeDao.save(employee);
return "redirect:/employee";
}
@PutMapping("/updateEmp")
public String updateEmp(Employee employee) {
employeeDao.save(employee);
return "redirect:/employee";
}
}
<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 http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com">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:annotation-driven/>
<mvc:default-servlet-handler/>
beans>