什么是restful编码风格?
1、统一资源接口
一个资源对应一个唯一的URI;
资源名可以使用单数,也可以使用复数,推荐复数。
URI中只能使用名词表示资源,不能使用动词。
比如:
学生资源URI:http://localhost:8080/students
老师资源URI:http://localhost:8080/teachers
2、资源的表述
对资源的操作,转换成请求的方式
原来对学生资源的增删改查操作请求:
http://localhost:8080/deleteStudent
http://localhost:8080/addStudent
http://localhost:8080/updateStudent
http://localhost:8080/selectStudent
restful:
查询Get http://localhost:8080/students
添加POST http://localhost:8080/students
修改PUT http://localhost:8080/students
删除DELETE http://localhost:8080/students
接口通过不同的请求方式找到对应的方法
即将 请求映射url,@RequestMapping(“url”) 改为下面四种
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
3、状态转移:
响应JSON数据格式:
{
code:操作的状态码,
message:操作的状态描述,
data:展示的数据
}
实现
(1)响应数据
创建一个泛型实体类,用于实现restful风格响应,
public class ResponseEntity<T> {
private int code;
private String message;
private T data;
}
@ResponseBody//设置返回数据为json格式,不止有一种返回数据的格式
@DeleteMapping("/url")
public ResponseEntity<Integer> deletePhoto(int pid){
int i = photoService.deletePhotoService(pid);
//响应数据
ResponseEntity re=new ResponseEntity<>(200,"ok",i);
return re;
}
(2)添加:
前端请求方式设为post
/url 代表某一资源,比如Students,Teachers等等
<form action="/url" method="post">
</form>
后端接口请求映射:
@PostMapping("/url")
(3)查询:
<a herf="/url">查询</a>
@GetMapping("/utl")
(4)删除与修改
注意:
在Ajax中,采用Restful风格PUT和DELETE请求传递参数无效,
传递到后台的参数值为null
原因:
Tomcat会将请求体中的数据,封装成一个map,
request.getParameter(“id”)就会从这个map中取值
SpringMvc封装POJO对象的时候,会进行request.getParamter()操作从map中获取值,
然后把值封装到POJO中去。
Tomcat一看是PUT请求或者DELETE请求,就不会把请求体中的key-value封装到map中,
只有POST形式的请求会才封装到map中去。
解决方案:
前端直接发送PUT或DELETE请求。
springMVC提供了一个过滤器:专门解析请求参数,封装map。
HiddenHttpMethodFilter
//web.xml中配置映射,使用HiddenHttpMethodFilter过滤器
<filter>
<filter-name>restful</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>restful</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
实现删除:
<form action="/url" method="delete">
</form>
@DeleteMapping("/url")
实现修改:
<form action="/url" method="put">
</form>
@PutMapping("/url")