目录

RESTful风格案例

# RESTful风格案例

前面我们一直使用/save这类意义明显的路径去标识URL 现在我们希望使用RESTful风格取代原有的写法 ![[Pasted image 20220615170835.png]]

# 请求配置

@Controller  
@RequestMapping("/users")  
public class UserController {  
    @RequestMapping(value = "",method = RequestMethod.GET)
    @ResponseBody   
    public String get(){  
        return "index.jsp";  
    }  
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    @ResponseBody  
    public String get(@PathVariable Integer id){  
        System.out.println("GET"+id);  
        return "index.jsp";  
    }  
  
    @RequestMapping(value = "",method = RequestMethod.POST)  
    @ResponseBody 
    public String post(){  
        return "index.jsp";  
    }  
  
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)  
    @ResponseBody  
    public String delete(@PathVariable Integer id){  
        System.out.println(id);  
        return "index.jsp";  
    }  
  
    @RequestMapping(value = "",method = RequestMethod.PUT) 
    @ResponseBody  
    public String put(){  
        return "index.jsp";  
    }  
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

在这个案例中,你能看到一些新东西,首先是method,在SprintMVC中支持8种请求方式,但实际上我们通常只会用到GET,POST,PUT,DELETE,此外我们用到了一个新的注释@PathVariable

![[Pasted image 20220615184211.png]]

# 简化开发

上面请求配置中,我们写了许多重复的代码,例如@ResponseBody,其实我们可以将其放到类上面,从而避免重复书写。

@Controller  
@ResponseBody
@RequestMapping("/users")  
public class UserController {  
	// ... 
}
1
2
3
4
5
6

SpringMVC也想到了这种情况,于是允许你使用一个注释进行整合 —— @RestController 该控制器是@Controller@ResponseBody的结合,因此可以省略写为:

@RestController
@RequestMapping("/users")  
public class UserController {  
	// ... 
}
1
2
3
4
5

此外,由于我们采用RESTful风格编写,因此上面有不少路径都是重复度很高的,我们可以优化成

@RestController  
@RequestMapping("/users")  
public class UserController {  
  
    @GetMapping  
    public String get(){  
        return "index.jsps";  
    }  
    @GetMapping("/{id}")  
    public String get(@PathVariable Integer id){  
        System.out.println("GET"+id);  
        return "index.jsp";  
    }  
  
    @PostMapping  
    public String post(){  
        return "index.jsp";  
    }  
  
    @DeleteMapping("/{id}/{user}")  
    public String delete(@PathVariable Integer id,@PathVariable String user){  
        System.out.println(id+user);  
        return "index.jsp";  
    }  
  
    @PutMapping  
    public String put(){  
        return "index.jsp";  
    }  
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
最近更新
01
基本知识
07-18
02
卷积神经网络识别图像
07-18
03
损失函数
07-18
更多文章>