一、相关注解说明
SpringBoot的Controller中经常会用到注解@Controller、@RestController、@RequestMapping、@RequestParam、@PathVariable、@RequestBody等。以下针对这些注解简单使用。
1、@Controller
用于定义控制器类,在spring项目中由控制器负责将用户发来的URL请求转发到对应的服务接口(service层),一般这个注解在类中,通常方法需要配合注解@RequestMapping。
@Controller
@RequestMapping("/demo")
public class HttpController {
@RequestMapping(value = "/hello")
public String sayHello() {
System.out.println("hello world!");
return "hello";
}
}
2、@RestController
用于定义控制器类,注解是@Controller和@ResponseBody的合集,表示这是个控制器bean,并且是将函数的返回值直接填入HTTP响应体中,是REST风格的控制器。
@RestController
@RequestMapping("/demo")
public class RestHttpController {
@RequestMapping(value = "/rest")
public Object rest() {
Map<String,Object> resultMap = new HashMap<>(8);
resultMap.put("msg","i am rest controller test");
resultMap.put("code","10000");
return resultMap;
}
}
请求返回:
{"msg":"i am rest controller test","code":"10000"}
3、@RequestMapping
作用于类或者方法上,用于映射URL路径,将http的请求地址映射到控制器(controller)类的处理方法上。
参数说明:
- value:定义处理方法的请求的 URL 地址。(重点)
- method:定义处理方法的 http method 类型,如 GET、POST 等。(重点)
- params:定义请求的 URL 中必须包含的参数。或者不包含某些参数。(了解)
- headers:定义请求中 Request Headers 必须包含的参数。或者不包含某些参数。(了解)
衍生注解:
- GetMapping:等价于@RequestMapping(value = “hello”, method = RequestMethod.GET),接收Get请求方法的RequestMapping。
- PostMapping:等价于@RequestMapping(value = “hello”, method = RequestMethod.POST),接收POST请求方法的RequestMapping。
- DeleteMapping&#x