RESTful
- 面向服务器资源
- REST风格提倡使用URL作为统一的风格设计,从前到后每个单词使用斜线分开,不适用问号键值对方式携带请求参数,而是将要发送给服务器的数据作为URL地址的一部分
- 而且RESTful不再在url中体现对资源的操作,而是通过请求的四种方式来表示对资源的操作:GET,POST,PUT,DELETE
- 访问同一个资源的路径都是一样的,通过改变请求方式来表示对资源的操作
- GET查询资源
- POST保存资源(保存新资源也可以,比如添加用户这种)
- DELETE删除资源
- PUT更新已有资源信息(修改资源)
RESTful实现
RESTful简单实现查询功能
- 假设我的@RequestMapping(“/user”)来处理请求
- 查询所有用户信息
- 由于是查询,请求方式为GET
- 设置控制器方法
@RequestMapping(value = "/user",method = RequestMethod.GET)
来处理查询请求,method一定要设置为GET - 在控制器方法中返回所有用户的数据
@RequestMapping(value = "/user",method = RequestMethod.GET)
public String getUser(){
System.out.println("获得所有用户数据");
return "sucess";
}
- 查询id为某个值的用户
- 比如所我要查询id为1的用户信息,那我RESTful风格的路径应该是这样
/uesr/1
@RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
,使用占位符来过去路径中的参数,格式如上多个参数就是多个斜杠加占位符- 在控制器方法中使用@PathVariable获取占位符对应的参数
@RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
public String getUserbyId(@PathVariable("id") int id){
System.out.println("获得id为"+id+"的user");
return "sucess";
}
RESTful简单实现添加功能
@RequestMapping(value = "/user",method = RequestMethod.POST)
public String addUser(){
System.out.println("添加用户信息");
return "sucess";
}
RESTful简单实现修改与删除
- 由于在html中的表单中只有get和post方法,没有delet和put请求方式,如何发送put和delet请求
- 使用过滤器
- 在Web.xml中注册HiddenHttpMethodFilter过滤器
<!-- 注册过滤器-->
<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或delete
- 当前请求必须为post
- 当前请求必须传输请求参数_method,value=“put"或者"delete”
- 在hmtl的form表单中请求方式为post且使用
<input type="hidden" name="_method" value="put">
- value设置为put和delete,表示请求方式为put或者delete,hidden则表示这个表单项目是隐藏的,用户看不见
@RequestMapping(value = "/user",method = RequestMethod.PUT)
public String modify(){
System.out.println("修改用户信息");
return "sucess";
}
@RequestMapping(value = "/user",method = RequestMethod.DELETE)
public String delete(){
System.out.println("删除用户信息");
return "sucess";
}
了解RESTful的简单实现功能后,我们可以用派生注解来代替
- GetMapping替代RequestMapping(method=GET)
- PutMapping替代RequestMapping(method=PUT)
- DeleteMapping替代RequestMapping(method=DELETE)
- PostMapping替代RequestMapping(method=POST)