springMVC-REST风格
注意:上述行为是约定方式,约定不是规范,可以打破,所以成REST风格,而不是REST规范。描述模块名称通常使用复数,也就是加s的格式描述,标识此类资源,而非单个资源,例如:users、books、accounts......
RESTful入门案例
@PathVariable是用来获取路径变量的。路径变量需要用大括号{}括起来,也可写多个变量,中间用/隔开,然后在下面设置形参接收。
value = "/users/{id}/{user}/{name}"
用于接收参数的三个注释:
RESTful快速开发
演示:
UserCOntroller类注解:
UserController类中的代码
//REST POST
@PostMapping
public String save(){
System.out.println("save running...");
return "perfect";
}
//REST DELETE
// @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
@DeleteMapping("/{id}")
public String delete(@PathVariable Integer id){
System.out.println("delete is running,id="+id);
return "{the action of delete is perfect}";
}
//REST GET
// @RequestMapping(method = RequestMethod.PUT)
@PutMapping
public String update(){
System.out.println("update is running...");
return "update perfect!";
}
// @RequestMapping(value = "/{id}",method = RequestMethod.GET)
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println("getById is running,id="+id);
return "getById is running and the final situation is perfect";
}
// @RequestMapping(method = RequestMethod.GET)
@GetMapping
public String getAll(){
System.out.println("getAll is running,and all the data has been got");
return "getAll is running and the final situation is perfect";
}
启动服务器后,使用postman发送各种请求:
基于RESTful页面数据交互
第二步操作不可省略,否则springMVC会将return "/pages/books.html" 当作一个页面返回(先前在配置中配置springMVC会拦截所有的"{/}"请求),导致访问不到web网页/pages/books.html。此设置含义为:当访问/pages/...的时候,走pages/目录下的内容,里面的"/js","/css",同样为此设置。配置完后应记得让SpringMvcConfig能扫到(在类上加上@Configuration注解,在SpringMvcConfig的@ComponentScan注解中添加路径)。
以上内容学自B站黑马课程