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());
    }
}
上一篇:SpringMVC


下一篇:SpringBoot中WebMVC模块儿如何实现自动配置?