@RequestParam、@PathVariable()、@RequestBody
1、用法
首先 @RequestParam、@PathVariable 通常获取放在url中的相关参数,而@RequestBody 是用来获取请求体的 body
@RequestParam、@PathVariable
http://localhost:8080/springmvc/hello/101?param1=10¶m2=20
@RequestMapping("/hello/{id}")
//@PathVariable 获取的是占位符{} 中的值
public String getDetails(@PathVariable(value="id") String id,
//@RequestParam 获取的是 ?xxx={} 等号后的值
@RequestParam(value="param1", required=true) String param1,
@RequestParam(value="param2", required=false) String param2){
.......
}
@RequestBody
我们通常需要定义实体类去接收, springMVC 框架会自动帮我们将前端传过来的 Json Body,通过视图解析器解析为标注了 @RequestBod 的实体类的相关属性(属性有的就解析出来,没有就不会设为 null)
@PostMapping("add")
public JSONObject addGraphicPublicity(@RequestBody @Valid GraphicPublicity graphicPublicity)
2、设计目的不同
@PathVariable 的设计目的,是为了用来请求资源路径的
@RequestParam 通常是提交数据,例如我们会这样设计URL:
/blogs/{blogId}:请求获取一篇博客资源,id为该篇博客的id
/blogs/blogId?state=0:设置某篇博客状态,state=0 表示不发布
另外值得注意的是, 我们可以通过 body 提交表单数据 和文件,这两样就是在 Body 中设置, Content-Type 类型分别为 application/x-www-form-urlencoded 和multipart/form-data,而获取时,可以使用 @ModelAttribute 和 MultipartFile来获取数据,或者直接通过 HttpServletRequest 传递进去后解析
form:
file:
@RequestBody 的类型为 application/json 表示 提交的是json数据