目录
RESTFul:Representational State Transfer,表现层资源状态转移。
资源是一种看待服务器的方式,就是将服务器看作是由很多离散的资源组成,每个资源是服务器上一个可命名的抽象概念。因为资源是一个抽象概念,所以它不仅仅能代表服务器文件系统中的一个文件、数据库的一张表等具体的东西,可以将资源设计的要多抽象就多抽象,只要想象力允许而且客户端应用开发者能够理解,与面向对象设计类似,资源以名词为核心来组织,首先关注的是名词。一个资源可以由一个或多个URI来标识。URI既是资源名称,也是资源在web上的地址。对某个资源感兴趣的客户端应用,可以通过资源的URI与其进行交互。
资源的表述是一段对于资源在某个特定时刻的状态的描述。可以在客户端-服务器端之间转移(交换)。资源的表述可以有多种格式,如HTML\XML\JSON\图片等。资源的表述格式可以通过协商机制来确定。请求--响应方向的表述通常使用不同的格式。
状态转移说的是:在客户端与服务器端之间转移代表资源状态的表述。通过转移和操作资源的表述来间接实现操作资源的目的。
在HTTP协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。
对应操作:GET用来获取资源、POST用来新建资源、PUT用来更新资源、DELETE用来删除资源。
REST风格提倡URL地址使用统一的风格设计,从前到后各个单词用斜杠分开,不使用问号键值对方式携带请求参数,而是将要发送给服务器的数据作为URL地址的一部分,以保证整体风格的一致性。
测试get和post请求
- @Controller
- public class UserController {
- @RequestMapping(value = "/user", method = RequestMethod.GET)
- public String getAllUser(){
- System.out.println("查询所有用户信息");
- return "success";
- }
- @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
- public String getUserById(){
- System.out.println("根据id查询用户信息");
- return "success";
- }
- @RequestMapping(value = "/user",method = RequestMethod.POST)
- public String insertUser(String username,String password){
- System.out.println(username +","+ password);
- return "success";
- }
- }
- html>
- <html lang="en" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>Titletitle>
- head>
- <body>
- <a th:href="@{/user}">查询所有用户信息a><br>
- <a th:href="@{/user/1}">根据用户id查询用户信息a><br>
- <form th:action="@{/user}" method="post">
- 用户名:<input type="password" name="password"><br>
- 密码:<input type="text" name="username"><br>
- <input type="submit" value="添加">
- form>
- body>
- html>
配置springMVC.xml实现跳转
- <mvc:view-controller path="/" view-name="index">mvc:view-controller>
- <mvc:view-controller path="/users" view-name="users">mvc:view-controller>
-
- <mvc:annotation-driven/>
测试put请求
- @RequestMapping(value = "/user",method = RequestMethod.PUT)
- public String updateUser(String username,String password){
- System.out.println("修改用户:"+username +","+ password);
- return "success";
- }
- <form th:action="@{/user}" method="post">
- <input type="hidden" name="_method" value="put"><br>
- 用户名:<input type="password" name="password"><br>
- 密码:<input type="text" name="username"><br>
- <input type="submit" value="添加">
- form><br>
在web.xml文件中配置HiddenHttpMethodFilter过滤器处理put和delete请求
-
- <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过滤器位置需要在CharacterEncodingFilter过滤器后面