文章目录
REST(Representational State Transfer,表述性状态转移),是一种架构风格,它提倡URL地址使用统一的风格:从前到后各个单词用斜杠分开,不使用 ?键值对 方式携带请求参数,而是将发送给服务器的参数作为URL地址的一部分,以保证整体风格的一致性。
HTTP协议中有4个常用的操作资源的方式,
- GET,用于获取资源(查询)。
- POST,用于新增资源(新增)。
- PUT,用于更新资源(更改)。
- DELETE,用于删除资源(删除)。
下面来比较下传统风格与REST风格下,上述四种操作方式的不同。
操作方式 | 传统风格 | REST风格 |
---|---|---|
查询(GET请求) | getUserById?id=1 | user/1 |
新增(POST请求) | saveUser | user |
更改(PUT请求) | updateUser | user |
删除 (DELETE请求) | deleteUser?id=1 | user/1 |
1. 新建maven项目rest
2. 修改pom.xml
修改pom配置文件 ,并添加依赖。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">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>rest</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.12</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.3.0-alpha10</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
3. 新增web模块,修改web.xml
web.xml的配置内容如下,主要配置了编码过滤器CharacterEncodingFilter和前端控制器DispatcherServlet。
<?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>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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
4. 新增SpringMVC配置文件
在resources目录下新建配置文件springMVC.xml,配置内容如下所示,主要配置了组件扫描component-scan和thymeleaf视图解析器ThymeleafViewResolver。
<?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">
<context:component-scan base-package="com.example.rest.controller"></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>
</beans>
5. 创建控制器
在java目录下新建Package:com.example.rest.controller,并在该Package下新建类RestController
,如下所示,
package com.example.rest.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class RestController {
@RequestMapping("/")
public String index(){
return "index";
}
@RequestMapping(value = "/user",method = RequestMethod.GET)
public String getAllUser(){
System.out.println("查询所有用户信息");
return "success";
}
@RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
public String getUserById(@PathVariable("id") Integer id){
System.out.println("根据id查询用户信息,id="+id);
return "success";
}
@RequestMapping(value = "/user",method = RequestMethod.POST)
public String insertUser(String username,String password){
System.out.println("插入用户,username="+username+" password="+password);
return "success";
}
@RequestMapping(value = "/user",method = RequestMethod.PUT)
public String updateUser(String username,String password){
System.out.println("更新用户,username="+username+" password="+password);
return "success";
}
@RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
public String deleteUser(@PathVariable("id") Integer id){
System.out.println("删除用户,id="+id);
return "success";
}
}
6. 创建视图文件
在WEB-INF下新建子目录templates,在templates下新建视图文件:index.html
和success.html
。
<!-- index.html -->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<a th:href="@{/user}">查询所有用户信息</a><br/><br/>
<a th:href="@{/user/1}">根据id查询用户信息</a><br/><br/>
<form th:action="@{/user}" method="post">
用户名:<input type="text" name="username" /><br/>
密码:<input type="password" name="password" /><br/>
<input type="submit" value="插入用户" />
</form><br/>
<form th:action="@{/user}" method="put">
用户名:<input type="text" name="username" /><br/>
密码:<input type="password" name="password" /><br/>
<input type="submit" value="更新用户" />
</form><br/>
<form th:action="@{/user/1}" method="delete">
<input type="submit" value="删除用户" />
</form>
</body>
</html>
<!-- success.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>success</title>
</head>
<body>
成功
</body>
</html>
7. 在本地tomcat中运行应用
由于浏览器只支持get和post,即使在form表单中设置method为put或delete,最后它们还是被当成get处理。
为了发送put请求和delete请求,Spring提供HiddenHttpMethodFilter。
8. 使用HiddenHttpMethodFilter发送put和delete请求
首先,在web.xml中添加HiddenHttpMethodFilter过滤器。
<?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>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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
<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>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
注意哈,此时web.xml中有两个过滤器:CharacterEncodingFilter和HiddenHttpMethodFilter。
过滤器的执行顺序有先有后,谁的fliter-mapping在前,谁就越先执行。
然后,修改index.html。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<a th:href="@{/user}">查询所有用户信息</a><br/><br/>
<a th:href="@{/user/1}">根据id查询用户信息</a><br/><br/>
<form th:action="@{/user}" method="post">
用户名:<input type="text" name="username" /><br/>
密码:<input type="password" name="password" /><br/>
<input type="submit" value="插入用户" />
</form><br/>
<form th:action="@{/user}" method="post">
<input type="hidden" name="_method" value="put"/>
用户名:<input type="text" name="username" /><br/>
密码:<input type="password" name="password" /><br/>
<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>
</body>
</html>
如何使用HiddenHttpMethodFilter来发送put和delete请求?需要做到以下两点:
- 当前的请求方式必须为post。
- 当前请求必须传输参数_mothod,参数值为put或delete。
HiddenHttpMethodFilter是如何实现转发put或delete请求的?看一下HiddenHttpMethodFilter的源码就能理解。
public class HiddenHttpMethodFilter extends OncePerRequestFilter {
private static final List<String> ALLOWED_METHODS;
public static final String DEFAULT_METHOD_PARAM = "_method";
private String methodParam = "_method";
public HiddenHttpMethodFilter() {
}
public void setMethodParam(String methodParam) {
Assert.hasText(methodParam, "'methodParam' must not be empty");
this.methodParam = methodParam;
}
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
HttpServletRequest requestToUse = request;
if ("POST".equals(request.getMethod()) && request.getAttribute("javax.servlet.error.exception") == null) {
String paramValue = request.getParameter(this.methodParam);
if (StringUtils.hasLength(paramValue)) {
String method = paramValue.toUpperCase(Locale.ENGLISH);
if (ALLOWED_METHODS.contains(method)) {
requestToUse = new HiddenHttpMethodFilter.HttpMethodRequestWrapper(request, method);
}
}
}
filterChain.doFilter((ServletRequest)requestToUse, response);
}
static {
ALLOWED_METHODS = Collections.unmodifiableList(Arrays.asList(HttpMethod.PUT.name(), HttpMethod.DELETE.name(), HttpMethod.PATCH.name()));
}
private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {
private final String method;
public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
super(request);
this.method = method;
}
public String getMethod() {
return this.method;
}
}
}
着重看下doFilterInternal
这个方法,
"POST".equals(request.getMethod())
,当前请求方法必须是post。private String methodParam = "_method";
String paramValue = request.getParameter(this.methodParam);
即String paramValue = request.getParameter("_method");
,当前请求方法必须包含参数_method
。ALLOWED_METHODS.contains(method)
ALLOWED_METHODS = Collections.unmodifiableList(Arrays.asList(HttpMethod.PUT.name(), HttpMethod.DELETE.name(), HttpMethod.PATCH.name()));
,故HiddenHttpMethodFilter可以转发put、delete和patch请求。
最后,重启应用。