WebMvc常用注解示例

WebMvc常用注解示例

  • 注册模型属性: @ModelAttribute
  • 读取请求头: @RequestHeader
  • 读取 Cookie: @CookieValue
  • 校验参数: @Valid 、@Validated
  • 注解处理: @ExceptionHandler
  • 切面通知: @ControllerAdvice

示例代码

  • HelloWorldController.java
@Controller
public class HelloWorldController {
    @RequestMapping("")
    public String index(@RequestParam(required = true) int value, Model model) {
        return "index";
    }
}
  • HelloWorldControllerAdvice.java
@ControllerAdvice(assignableTypes = HelloWorldController.class)
public class HelloWorldControllerAdvice {
    @ModelAttribute("acceptLanguage")
    public String acceptLanguage(@RequestHeader("Accept-Language") String acceptLanguage){
        return acceptLanguage;
    }
    @ModelAttribute("jsessionId")
    public String jsessionId(@CookieValue("JSESSIONID") String jsessionId){
        return jsessionId;
    }
    @ModelAttribute("message")
    public String message(){
        return "Hello,World";
    }
    @ExceptionHandler(Throwable.class)
    public ResponseEntity<String> onException(Throwable throwable) {
        return ResponseEntity.ok(throwable.getMessage());
    }
}
posted @ 2020-06-04 08:51  樊梨花大大王  阅读(153)  评论(0编辑  收藏  举报