使用 @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) {…}