使用 @Controller 注释对将成为 MVC 中控制器的类进行注释并处理 HTTP 请求。
@RequestMapping
使用 @RequestMapping 注释对函数进行注释,该函数处理某些 HTTP 方法、URI 或 HTTP 头。此注释是 Spring REST 支持的关键。可以更改 method 参数以处理其他 HTTP 方法。
例如:
@RequestMapping(method=RequestMethod.GET, value="/emps",
headers="Accept=application/xml, application/json")
headers 限定 只有请求头中 Accept 有 application/xml, application/json这样匹配的字符串才受理
以下是一次请求的报文头
headers 类容
security-3.1新增的参数
2: @RequestMapping 新增参数Consumes 和Produces
前面介绍过@RequestMapping的参数中有一个header的参数,来指定handler method能接受的http request 请求的header内容。
而consumes和produces则更进一步,直接指定所能接受或产生的request请求的content type。
例如
表示handlermethod接受的请求的header中的 Content-Type为text/plain;
Accept为application/json
4:
Validation For @RequestBody
@RequestBody现在直接支持@valid标注了,如果validation失败,将抛出
RequestBodyNotValidException。
具体处理逻辑可见 spring 中的RequestResponseBodyMethodProcessor中的以下代码。
- public Object resolveArgument(MethodParameter parameter,
- ModelAndViewContainer mavContainer,
- NativeWebRequest webRequest,
- WebDataBinderFactory binderFactory) throws Exception {
- Object arg = readWithMessageConverters(webRequest, parameter, parameter.getParameterType());
- if (shouldValidate(parameter, arg)) {
- String argName = Conventions.getVariableNameForParameter(parameter);
- WebDataBinder binder = binderFactory.createBinder(webRequest, arg, argName);
- binder.validate();
- Errors errors = binder.getBindingResult();
- if (errors.hasErrors()) {
- throw new RequestBodyNotValidException(errors);
- }
- }
- return arg;
- }
@PathVariable
使用 @PathVariable 注释可将 URI 中的路径变量作为参数插入。例如:
@RequestMapping(method=RequestMethod.GET, value="/emp/{id}")
public ModelAndView getEmployee(@PathVariable String id) { … }
其他有用的注释
使用 @RequestParam 将 URL 参数插入方法中。
使用 @RequestHeader 将某一 HTTP 头插入方法中。
使用 @RequestBody 将 HTTP 请求正文插入方法中。
使用 @ResponseBody 将内容或对象作为 HTTP 响应正文返回。
使用 HttpEntity<T> 将它自动插入方法中,如果将它作为参数提供。
使用 ResponseEntity<T> 返回具有自定义状态或头的 HTTP 响应。
例如:
public @ResponseBody Employee getEmployeeBy(@RequestParam("name")
String name, @RequestHeader("Accept") String accept, @RequestBody String body) {…}
public ResponseEntity<String> method(HttpEntity<String> entity) {…}