赞
踩
SpringBoot Controller接收参数的几种常用注解方式,
1、请求路径中带参数 使用 @PathVariable 获取路径参数。即url/{id}这种形式。
对应的java代码:
@GetMapping("/student/{id}")
public void demo(@PathVariable(name = "id") String id, @RequestParam(name = "name") String name) {
System.out.println("id="+id);
System.out.println("name="+name);
}
2、@RequestParam 获取查询参数。即url?name=这种形式 用于get/post。springboot默认情况就是它,类似不写注解
对应的java代码:
@PostMapping(path = "/demo1")
public void demo1(@RequestParam Student stu) {
System.out.println(stu.toString());
}
3、@RequestBody获取POST请求参数
对应的java代码:
@PostMapping(path = "/demo1")
public void demo1(@RequestBody Student stu) {
System.out.println(stu.toString());
}
4请求头参数以及Cookie
1、@RequestHeader
2、@CookieValue
最开始支持的是get和post请求,因此写法如下:
@GetMapping("/demo3")
public void demo3(@RequestHeader(name = "myHeader") String myHeader,
@CookieValue(name = "myCookie") String myCookie) {
System.out.println("myHeader=" + myHeader);
System.out.println("myCookie=" + myCookie);
}
也可以这样
@GetMapping("/demo3")
public void demo3(HttpServletRequest request) {
System.out.println(request.getHeader("myHeader"));
for (Cookie cookie : request.getCookies()) {
if ("myCookie".equals(cookie.getName())) {
System.out.println(cookie.getValue());
}
}
}
@RequestMapping(value = "/queryAddressById", method = {RequestMethod.GET, RequestMethod.POST})
public WebResp addAddress(HttpServletRequest request,
UserAddressParam addressParam) throws Exception {
JSONObject.toJSON(addressParam));
UserAddressResult result =
return WebResp.getSuccessInstance(result);
}
我的需求里与前端沟通【修改或者新增操作数据这种操作最好用post请求】前端通过https协议请求后台接口,发post请求,并将数据放在RequestBody,以json形式传输,后来修改成
@RequestMapping(value = "/queryAddressById", method = {{RequestMethod.GET, RequestMethod.POST})
public WebResp addAddress(HttpServletRequest request,
@RequestBody UserAddressParam addressParam) throws Exception {
JSONObject.toJSON(addressParam));
UserAddressResult result =
return WebResp.getSuccessInstance(result);
}
报下面的异常,所以进行修改代码,将支持的get请求RequestMethod.GET去掉,请求正常了。
org.springframework.http.converter.HttpMessageNotReadableException: I/O error while reading input message; nested exception is java.io.IOException: Stream closed
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。