SpringBoot请求参数注入的方式
请求模式
GET方式:用于简单查询,使用注解:@GetMapping("/hello")或者@RequestMapping(value = “hello”, method = RequestMethod.GET)
POST方式:用于复杂查询或数据添加,使用注解:@PostMapping("/person/add")或者@RequestMapping(value = “/person/add”, method = RequestMethod.POST)
HEAD、PUT、PATCH、DELETE、OPTIONS、TRACE等方式不常用(反正我做的项目里没有用这几种)
参数注入方式
@RequestParam
@RestController
@RequestMapping(value = "/banner")
public class BannerController {
@RequestMapping(value = "/test", method = RequestMethod.GET)
@ResponseBody
public String test(@RequestParam Integer id) {
System.out.println(id);
return "1111";
}
}
请求方式:http://localhost:8082/v1/banner/test?id=1
@PathVariable
@RestController
@RequestMapping(value = "/banner")
public class BannerController {
@RequestMapping(value = "/test/{id}", method = RequestMethod.GET)
@ResponseBody
public String test(@PathVariable Integer id) {
System.out.println(id);
return "1111";
}
}
请求方式:http://localhost:8082/v1/banner/test/1
@PathVariable和@RequestParam
@RestController
@RequestMapping(value = "/banner")
public class BannerController {
@RequestMapping(value = "/test/{id}", method = RequestMethod.GET)
@ResponseBody
public String test(@PathVariable Integer id, @RequestParam String name) {
System.out.println(id);
System.out.println(name);
return "1111";
}
}
请求方式:http://localhost:8082/v1/banner/test/1?name=ss
备注
@PathVariable和@RequestParam注解,我一般用在get请求方法中,Content-Type 为 application/x-www-form-urlencoded、application/json都可以
@RequestBody
当请求方式为post请求,且content-type为application-json的时候
@RequestMapping(value = "register.do", method = RequestMethod.POST)
@ResponseBody
public ServerResponseJsonResult register(@RequestBody UserBO userBO) {
System.out.println(userBO.getUsername());
return ServerResponseJsonResult.ok();
}
备注
如果使用@RequestBody,那么接收参数必须是以对象形式,比如UserBO userBO,不能是String username这种,不然会报错
备注
使用对象传参,对象里定义的变量名必须是小写,如果有大写字母,后端接收到的是null(这是由于序列化插件配置引起的,我的项目里用的是jackJson,之前在application.yml文件里配置了参数必须是下划线格式,所以不能传驼峰格式的参数)
为什么java里不像其他语言一样,只要请求参数和代码里的一致就行,还需要@PathVariable、@RequestParam这样的注解来表明url中传入的参数?
原因是在SpringBoot中,方法里除了url传入的参数,还可以通过依赖注入的方式传入参数。所以就需要用注解标明url传入的参数