REST(Representational State Transfer),表现形式状态转换,它是一种软件架构风格 当我们想表示一个网络资源的时候,可以使用两种方式:
- //@Controller
- //@ResponseBody配置在类上可以简化配置,表示设置当前每个方法的返回值都作为响应体
- //@ResponseBody
- @RestController //使用@RestController注解替换@Controller与@ResponseBody注解,简化书写
- @RequestMapping("/books")
- public class BookController {
-
- // @RequestMapping( method = RequestMethod.POST)
- @PostMapping //使用@PostMapping简化Post请求方法对应的映射配置
- public String save(@RequestBody Book book){
- System.out.println("book save..." + book);
- return "{'module':'book save'}";
- }
-
- // @RequestMapping(value = "/{id}" ,method = RequestMethod.DELETE)
- @DeleteMapping("/{id}") //使用@DeleteMapping简化DELETE请求方法对应的映射配置
- public String delete(@PathVariable Integer id){
- System.out.println("book delete..." + id);
- return "{'module':'book delete'}";
- }
-
- // @RequestMapping(method = RequestMethod.PUT)
- @PutMapping //使用@PutMapping简化Put请求方法对应的映射配置
- public String update(@RequestBody Book book){
- System.out.println("book update..."+book);
- return "{'module':'book update'}";
- }
-
- // @RequestMapping(value = "/{id}" ,method = RequestMethod.GET)
- @GetMapping("/{id}") //使用@GetMapping简化GET请求方法对应的映射配置
- public String getById(@PathVariable Integer id){
- System.out.println("book getById..."+id);
- return "{'module':'book getById'}";
- }
-
- // @RequestMapping(method = RequestMethod.GET)
- @GetMapping //使用@GetMapping简化GET请求方法对应的映射配置
- public String getAll(){
- System.out.println("book getAll...");
- return "{'module':'book getAll'}";
- }
- }
- //标准REST风格控制器开发
- @RestController
- @RequestMapping("/books")
- public class BookController2 {
-
- @PostMapping //添加
- public String save(@RequestBody Book book){
- System.out.println("book save..." + book);
- return "{'module':'book save'}";
- }
-
- @DeleteMapping("/{id}")
- public String delete(@PathVariable Integer id){
- System.out.println("book delete..." + id);
- return "{'module':'book delete'}";
- }
-
- @PutMapping //修改
- public String update(@RequestBody Book book){
- System.out.println("book update..."+book);
- return "{'module':'book update'}";
- }
-
- @GetMapping("/{id}") //get是查询
- public String getById(@PathVariable Integer id){
- System.out.println("book getById..."+id);
- return "{'module':'book getById'}";
- }
-
- @GetMapping
- public String getAll(){
- System.out.println("book getAll...");
- return "{'module':'book getAll'}";
- }
- }
注意:要在SpringConfig配置类中加上 @EnableWebMvc 注解,目前用来解析json格式,此注解功能很多
-
- @Configuration
- @ComponentScan("com.itheima.controller")
- @EnableWebMvc
- public class SpringMvcConfig {
- }