REST(Representation State Transfer) ,表现形态切换
传统风格URL:http://localhost/user/getById?id=1
http://localhost/user/saveUser
REST风格:http://localhost/user/user/1
http://localhost/user
优点: 书写简单,同时隐藏资源的访问行为,用户不发通过地址栏得知对资源进行了何种操作
我们可以根据REST风格访问资源时使用的行为动作区分对资源进行何种操作
用REST风格对资源进行访问成为RESTful
上述行为只是约定方式,约定不是规范,可以打破,所以我们称REST风格,而不是REST规范
映射 URL 绑定的占位符
通过 @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过
若方法参数名称和需要绑定的url中变量名称不一致时,写成:
@RequestMapping("/getUserById/{name}")
public User getUser(@PathVariable("name") String userName){
return userService.selectUser(userName);
}
相当于@Controoler和@ResponseBody的整合
等同于:@RequestMapping(value = “/save”, method = RequestMethod.POST)'
接收新增请求
- @PostMapping
- public String save(@RequestBody User user){
- System.out.println("save Test...."+user);
- return "{'model':'save test'}";
- }
等同于:@RequestMapping(value = “/save”, method = RequestMethod.GET)
接收查询请求
- @GetMapping("/{id}")
- public String getById(@PathVariable String id){
- System.out.println("getById Test...."+id);
- return "{'model':geyById test}";
- }
-
- @GetMapping()
- public String getAll(){
- System.out.println("getAll Test....");
- return "{'model':getAll test}";
- }
等同于:@RequestMapping(value = “/save”, method = RequestMethod.DELETE)
接收删除请求
- @DeleteMapping("/{id}")
- public String delete(@PathVariable String id){
- System.out.println("delete Test...."+id);
- return "{'model':delete test}";
- }
等同于:@RequestMapping(value = “/save”, method = RequestMethod.PUT)
接收修改请求
- @PutMapping
- public String update(@RequestBody User user){
- System.out.println("update Test...."+user);
- return "{'model':update test}";
- }
新建SpringMvcSupport配置类
- package config;
-
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
-
-
-
- public class SpringMvcSupport extends WebMvcConfigurationSupport {
-
- @Override
- protected void addResourceHandlers(ResourceHandlerRegistry registry) {
- registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
- registry.addResourceHandler("/js/**").addResourceLocations("/js/");
- registry.addResourceHandler("/css/**").addResourceLocations("/css/");
- registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
- }
- }
在SpringMvc总配置类import上述类
@Import(SpringMvcSupport.class)
