RestFul风格讲解
Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。
/*
普通传参: http://localhost:8080/add?a=1&b=2
restful风格传参:http://localhost:8080/add/a/b
http://localhost:8080/add/1/2
*/
代码理解
package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@Controller
public class RestFulController {
@GetMapping("/add/{a}/{b}")
public String test1(@PathVariable int a,@PathVariable int b, Model model){
int res=a+b;
model.addAttribute("msg","结果为"+res);
return "test";
}
}
/*
@PathVariable RestFul要用这个
@GetMapping("/add/{a}/{b}") 相当于 @RequestMapping(name="/add/{a}/{b}",method = RequestMethod.GET)
还有其他别名 value,path
@RequestMapping(value="/add/{a}/{b}",method = RequestMethod.GET)
@RequestMapping(path="/add/{a}/{b}",method = RequestMethod.GET)
当然这些很少用!都是用@GetMapping("/add/{a}/{b}") 这种组合注解的
类似的还有以下这个
@DeleteMapping()
@PostMapping() 只能用post请求
*/
@Controller
public class RestFulController {
@GetMapping("/add/{a}/{b}")
public String test1(@PathVariable int a,@PathVariable int b, Model model){
int res=a+b;
model.addAttribute("msg","结果1为"+res);
return "test";
}
@PostMapping("/add/{a}/{b}")
public String test2(@PathVariable int a,@PathVariable int b, Model model){
int res=a+b;
model.addAttribute("msg","结果2为"+res);
return "test";
}
}
//地址可以一样,提交方式不同,走的方法不同
本文深入探讨了Restful风格的API设计,通过实例展示了如何使用Spring框架的注解实现GET和POST请求的方法映射。文章指出,Restful风格使得URL更加直观,参数传递更加简洁,易于理解和实现缓存。同时,提供了代码示例解释了如何使用`@GetMapping`和`@PostMapping`注解处理不同的HTTP请求方法。
2687

被折叠的 条评论
为什么被折叠?



