1.RESTful --一种风格
1.1RESTful简介
REST:Representational State Transfer,表现层资源状态转移。
①资源:一切皆资源
资源是一种看待服务器的方式,即,将服务器看作是由很多离散的资源组成,每个资源是服务器上一个可命名的抽象概念,因为资源是一个抽象的概念,所以它不仅仅能代表服务器文件系统的一个文件,数据库中的一张表等等具体的东西,可以将资源设计的要多抽象有多抽象,只要想象力允许而且客户端应用开发者能够理解.
与面向对象设计类似,资源是以名词为核心来组织的,首先关注的是名词,一个资源可以由一个或者多个URL来标识,URL既是资源的名称,也是资源在web上的地址.对某个资源感兴趣的客户端应用,可以通过资源的URL与其进行交互
例如:需要访问用户资源(user) URL:“/user” 不用管对资源的操作内容,只需要知道是这个资源就好:
RESTful实现
具体说,就是HTTP协议里面,四个表示操作方式的动词
GET: 用来 获取资源
POST:用来 新建资源
PUT:用来 更新资源
DELETE: 用来 删除资源
REST风格提倡URL地址使用统一的风格设计,从前到后各个单词使用斜杆分开**,不使用问号键值**对方式携带请求参数,而是要将要发送给服务器的数据作为URL地址的一部分,以保证整体风格的一致性
操作 | 传统方式 | REST风格 |
---|---|---|
查询操作 | getUserById?id=1 | user/1 ----->get请求方式 |
保存操作 | saverUser | user ----->post请求方式 |
删除操作 | deleteUser?id = 1 | user/1 ---->delete请求方式 |
更新操作 | updateUser | user ------>put请求方式 |
② 资源的表述
是一段对于资源在某个特定的时刻的状态的描述,可以在客户端-服务器端之间转移(交换),
资源的表述可以由很多种格式,例如HTML/XML/JSON/纯文本/图片/视频/音频等等,
资源的表述格式可以通过协商机制来确定,请求-响应方向的表述通常使用的不同的格式
③状态转移
状态转移说的是: 在客户端和服务器之间转移,(transfer)代表资源状态的表述,通过转移和操作资源的表述,来间接实现操作资源的目的
代码实现功能:
- 查询所有的用户信息: /user---->get请求
- 查询指定id的用户信息: /user/1---->get请求
- 添加用户信息: /user----> post请求
- 修改用户信息: /user---->put请求
- 根据id删除的用户信息: /user/1---->get请求
建立一个快速的maven-web项目
pom文件如下:
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 自动扫描包 -->
<context:component-scan base-package="com.atguigu.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"></mvc:view-controller>
</beans>
SpringMVC的配置文件
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 自动扫描包 -->
<context:component-scan base-package="com.atguigu.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"></mvc:view-controller>
</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">
<!--过滤器 编码问题-->
<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>
<!--设置springMvc的前端控制器-->
<servlet>
<servlet-name>springmvc</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>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
建立首页(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>
<h1> index.html</h1>
<a th:href="@{/user}">查询所有的用户信息</a><br>
<a th:href="@{/user/1}">查询id=1的用户信息</a>
</body>
</html>
success.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>成功跳转</title>
</head>
<body>
<h1>successly</h1>
</body>
</html>
建立java控制器方法类,向index.html中实现方法
1.查询所有的用户信息: /user---->get请求
2.查询id = 1 用户信息: /user---->get请求
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* 查询所有的用户信息: /user---->get请求
*/
@Controller
public class TestRestController {
@RequestMapping(value = "/user",method = RequestMethod.GET)
public String getAllUser(){
System.out.println(" 查询所有的用户信息: /user---->get请求");
return "success";
}
@RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
public String getUserById(@PathVariable("id") Integer id){
System.out.println("查询指定id的用户信: /user/1---->get请求");
return "success";
}
}
发送到tomcat服务器上运行tomcat服务器
3.添加用户信息 ----->post提交
因为是post提交,所以我们新建一个表单在index.html中
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="@{/user}">查询所有的用户信息</a><br>
<a th:href="@{/user/1}">查询id=1的用户信息</a>
<form th:action="@{/user}" method="post">
<input type="submit" th:value="添加用户信息"/>
</form>
</body>
</html>
控制器方法:
@RequestMapping(value = "/user",method = RequestMethod.POST)
public String insertUser(){
System.out.println("添加用户信息 /user ---->post");
return "success";
}
4.修改用户信息
因为form表单来说只有POST 和 GET请求,而修改用户信息需要PUT请求,我们强制性把method 设置为 PUT并不能实现PUT请求,这是需要设置过滤器来设置请求方式
注意: 对于多个过滤器时一定要把对于设置字符编码的过滤器放在首位
web.xml:
<!--设置处理请求的过滤器-->
<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>
配置了过滤器之后,发送的请求要满足两个条件,才能将请求方式转化为PUT or DELETE
- 要求1:请求方式必须是POST(HiddenHttpMethodFilter的doFilter方法)
- 要求2:必须在请求中传输过去一个请求参数:_method
要求1:
[第一个判断条件成立 必须是method = POST] &&
[第二个判断条件代表里面为空,找到异常,在当前条件异常肯定为空]
故第一个条件必须成立 才能进入 If 的判断中
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) {
//获取请求参数 private String methodParam = "_method" [括号内]
String paramValue = request.getParameter(this.methodParam);
//hasLength来判断 获取的请求参数是否有长度 判断是否为空
//如果 paramValue != null 或字符串长度不为 0 则进入,说明传入了请求参数
if (StringUtils.hasLength(paramValue)) {
//toUpperCase ()转化为大写
String method = paramValue.toUpperCase(Locale.ENGLISH);
// 判断是否包含_method的值转化大写的结果
// 是否为 PUT/DELETE/PATCH中的 一个
if (ALLOWED_METHODS.contains(method)) {
requestToUse = new HiddenHttpMethodFilter.HttpMethodRequestWrapper(request, method);
}
}
}
//1.若不进入 if直接放行 不拦截,即PUT/DELETE失败
//2.进入if 进行了替换的 requestToUse副本供使用
filterChain.doFilter((ServletRequest)requestToUse, response);
}
index.html
<form th:action="@{/user}" method="post">
<input type = "hidden" name="_method" th:value="put">
<input type="submit" th:value="修改用户信息">
</form>
控制器方法:
@RequestMapping(value = "/user",method = RequestMethod.PUT)
public String updatetUser(){
System.out.println("修改用户信息 /user ---->put");
return "success";
}
5.删除id = 1的用户的信息(同 PUT请求方法)
需要通过一个表单来删除,功能就变得很麻烦
<form th:action="@{/user/1}" method="post">
<input type = "hidden" name="_method" th:value="delete">
<input type="submit" th:value="删除用户信息">
</form>
控制器方法:
@RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
public String deleteUser(@PathVariable("id") Integer id){
System.out.println("删除用户信息 /user ---->delete请求");
return "success";
}
2.在控制器方法中的@RequestMapping的派生注解的应用
1.GET请求[查询]
// @RequestMapping(value = "/user",method = RequestMethod.GET)
@GetMapping("/user")
public String getAllUser(){
System.out.println("查询所有的用户信息: /user---->get请求");
return "success";
}
// @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
@GetMapping("/user/{id}")
public String getUserById(@PathVariable("id") Integer id){
System.out.println("查询指定id的用户信: /user/1---->get请求");
return "success";
}
POST请求[添加用户信息]
// @RequestMapping(value = "/user",method = RequestMethod.POST)
@GetMapping("/user")
public String insertUser(){
System.out.println("添加用户信息 /user ---->post");
return "success";
}
PUT请求[修改用户信息]
// @RequestMapping(value = "/user",method = RequestMethod.PUT)
@PutMapping("/user")
public String updateUser(){
System.out.println("修改用户信息 /user ---->put");
return "success";
}
DELETE请求[删除用户请求]
// @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
@DeleteMapping("/user/{id}")
public String deleteUser(@PathVariable("id") Integer id){
System.out.println("删除用户信息 /user ---->put");
return "success";
}
重新部署tomcat