Spring REST风格
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
RESTRepresentational State Transfer表现形式状态转换,它是一种软件架构风格。
当我们想要表示一个网络资源时传统方式通常是用一个请求url表示一个操作。这样既不方便也不安全因为操作对于用户是透明的可以通过地址得知要实现的是什么操作。
为了解决这样的问题可以使用REST风格表示网络资源。
这样请求地址变的简单了并且光看请求URL并不是很能猜出来该URL的具体功能。
但是我们的需求不只有保存我们目标实现增删改查而url只有一个怎么办呢
所以REST风格访问资源时使用行为动作区分对资源进行了何种操作
http://localhost/users
查询全部用户信息 GET查询http://localhost/users/1
查询指定用户信息 GET查询http://localhost/users
添加用户信息 POST新增/保存http://localhost/users
修改用户信息 PUT修改/更新http://localhost/users/1
删除用户信息 DELETE删除
上述行为是约定方式约定不是规范可以打破所以称REST风格而不是REST规范。
描述模块的名称通常使用复数也就是加s的格式描述表示此类资源而非单个资源例
如:users、books、accounts…
添加示例
@Controller
public class UserController {
//设置当前请求方法为POST表示REST风格中的添加操作
@RequestMapping(value = "/users",method = RequestMethod.POST)
@ResponseBody
public String save() {
System.out.println("user save...");
return "{'module':'user save'}";
}
}
删除示例
@Controller
public class UserController {
//设置当前请求方法为DELETE表示REST风格中的删除操作
@RequestMapping(value = "/users",method = RequestMethod.DELETE)
@ResponseBody
public String delete(Integer id) {
System.out.println("user delete..." + id);
return "{'module':'user delete'}";
}
}
修改示例
@Controller
public class UserController {
//设置当前请求方法为PUT表示REST风格中的修改操作
@RequestMapping(value = "/users",method = RequestMethod.PUT)
@ResponseBody
public String update(@RequestBody User user) {
System.out.println("user update..." + user);
return "{'module':'user update'}";
}
}
根据ID查询示例
@Controller
public class UserController {
//设置当前请求方法为GET表示REST风格中的查询操作
@RequestMapping(value = "/users/{id}" ,method = RequestMethod.GET)
@ResponseBody
public String getById(@PathVariable Integer id){
System.out.println("user getById..."+id);
return "{'module':'user getById'}";
}
}
查询全部示例
@Controller
public class UserController {
//设置当前请求方法为GET表示REST风格中的查询操作
@RequestMapping(value = "/users" ,method = RequestMethod.GET)
@ResponseBody
public String getAll() {
System.out.println("user getAll...");
return "{'module':'user getAll'}";
}
}
如果value中的变量名和控制类需要的变量名不一样或者打算传递多个参数时可以使用@PathVariable
注解
例如
@Controller
public class UserController {
//设置当前请求方法为DELETE表示REST风格中的删除操作
@RequestMapping(value = "/users/{id}/{name}",method = RequestMethod.DELETE)
@ResponseBody
public String delete(@PathVariable Integer id,@PathVariable String name)
{
System.out.println("user delete..." + id+","+name);
return "{'module':'user delete'}";
}
}
总结
设定Http请求动作(动词)
@RequestMapping(value="",method = RequestMethod.POST|GET|PUT|DELETE)
设定请求参数(路径变量)
@RequestMapping(value="/users/{id}",method = RequestMethod.DELETE)
@ReponseBody
public String delete(@PathVariable Integer id){
}