controller层中涉及到的注解:
参考链接:https://blog.csdn.net/weixin_41404773/article/details/80319083
1、RequestParam
RequestParam用在方法的参数前面
@GetMapping("/chartsData")
public ServerResponse<ChartDataVo> getData(@RequestParam("itemName") String itemName,@RequestParam("analyseId") String analyseId) {
return ServerResponse.createBySuccess(spcMapper.getChartsData(itemName, analyseId));
}
2、PathVariable
PathVariable为路径变量,参数与大括号的名字要相同
@RequestMapping("user/get/mac/{macAddress}")
public String getByMacAddress(@PathVariable String macAddress){
//do something;
}
3、Responsebody
@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"));
}
改注释表示方法的返回结果直接写入HTTP responsebody中
一般在异步获取数据时使用,在使用@RequestMapping后,返回值通常解析为跳转路径,加上@responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。比如异步获取json数据,加上@responsebody后,会直接返回json数据。
注:require=false后可以允许传入的对象为空,即前端可传可不传
require=true表示必须传值
@PostMapping(value = "find")
@ResponseBody
public void list(@RequestBody(required = false) RequestMode requestMode){
return userService.findByName(requestMode.getName());
}
4、RequestBody
该注解能够将页面端传递的json字符串转换为对应的java Object
controller层涉及到的请求方式
1、get请求方式
get方式和post不同,不接受josn方式传递,可以通过路径传递参数,常用的注解
@GetMapping(value = "find/{name}")
//http://localhost:8080/find/张三
@ResponseBody
public void list(@PathVariable String name){
return userService.findByName(name);
}
@GetMapping(value = "find")
//http://localhost:8080/find?name=张三
@ResponseBody
public void list(@RequestParam(value = "name") String name){
return userService.findByName(name);
}
2、post请求方式
post方式最好的方式是用josn格式,,在cotroller层对象前加注解@RequestBody将数据和前端映射,前端会将json或者thml格式的数据存入body缓冲区传到controller
@ResponseBody会将获取的数据以json的格式返回
@PostMapping(value = "find")
@ResponseBody
public void list(@RequestBody(required = false) RequestMode requestMode){
return userService.findByName(requestMode.getName());
}
@PostMapping(value = "find")
@ResponseBody
public void list(@RequestParam(value = "name") String name){
return userService.findByName(name);
}
网友评论