Controller层常用的注解
注解 | 作用 |
---|---|
@Controller | 处理http请求 |
@RestController | 与@ResponseBody配合@Controller相同。用于返回Json |
@PathVariable | 获取url中的参数 |
@RequestParam | 获取请求参数的值 |
@RequestMapping | 配置url映射,需要多个时可以将value写成一个集合 |
@GetMapping | 组合注解,相当于@RequestMapping(method = RequestMethod.GET) |
@PostMapping | 组合注解,相当于@RequestMapping(method = RequestMethod.POST) |
@PathVariable
@RequestMapping("/getuserid/{id}")
public AjaxMessage getUser(@PathVariable("id") int id) {
User user = userService.querUserById(id);
if (user != null) {
return new AjaxMessage(true, "", user);
}else {
return new AjaxMessage(false, "没有数据", null);
}
}
@RequestParam
@RequestMapping("/getuserpwd")
public AjaxMessage getUserPwd(@RequestParam("pwd") String password) {
List<User> userList = userService.queryUserByPwd(password);
if (userList != null) {
return new AjaxMessage(true,"",userList);
}else {
return new AjaxMessage(false, "没有数据", new ArrayList<User>());
}
}
@RequestBody
@PostMapping(path = "/demo1")
public void demo1(@RequestBody Person person) {
System.out.println(person.toString());
}
也可以是
@PostMapping(path = "/demo1")
public void demo1(@RequestBody Map<String, String> person) {
System.out.println(person.get("name"));
}
可选参数
属性required = true/false 代表这个参数选填
- 在@PathVariable注解中,在@RequestMapping中,需列出各个url格式
@RequestMapping(value = {
"/checkidpv/{item}/{area}/{location}", "/checkidpv/{item}/{area}", "/checkidpv/{item}",
"/checkidpv" }, method = RequestMethod.GET)
public Object getSpotByIdPV(@PathVariable(value = "item", required = false) String item,
@PathVariable(value = "area", required = false) String area,
@PathVariable(value = "location", required = false) String location) {
// function body
}
- 在@RequestParam中,该属性写在注解中。另外,通过defaultValue属性设置默认值
@RequestMapping(value = "/checkidrq", method = RequestMethod.GET)
public Object getSpotByIdRP(@RequestParam(value = "item",required = false) String item, @RequestParam(value = "area",required = false) String area,
@RequestParam(value = "location",required = false) String location) {
// function body
}