• 周六. 10 月 5th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Two applications of @ controlleradvice in spring MVC

King Wang

1 月 3, 2022

SpringMVC in @ControllerAdvice Two applications of

1. exception handling @ExceptionHandler

1.1 Global exception handling

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handlerException(Exception ex) {

ex.printStackTrace();
return new Result(false, StatusCode.ERROR, ex.getMessage());
}
}

1.2 Appoint Controller Catch exception handling

@ControllerAdvice(assignableTypes = AsynController.class)

1.3 Catch custom exception

 /*
todo Customize an exception class , It can also deal with different situations
*/
@ExceptionHandler(value = UserNotFoundException.class)
@ResponseBody
public Map<String, Object> handlerUserNotFoundException(UserNotFoundException ex) {

ex.printStackTrace();
Map<String, Object> result = new HashMap<>();
return result;
}

2. Unified management Model attribute @ModelAttribute

hold Request Medium Cookies Set to Model in , Easy to manage , It’s also convenient for later refactoring Controller.

@ControllerAdvice(assignableTypes = AsynController.class)
public class ModelAttributeHandler {

@ModelAttribute("token")
public String token(@RequestHeader("token") String token){

return token;
}
@ModelAttribute("jsessionId")
public String sessionId(@CookieValue("JSESSIONID") String sessionId){

return sessionId;
}
}

It is worth noting that

 @RequestMapping(value = "/helloWorld.do")
@ModelAttribute("attributeName")
public String helloWorld() {

return "hi";
}

If @RequestMapping and @ModelAttribute At the same level , The return is no longer a view name , It is Model Of value, The view name resolves to helloworld

more @ModelAttribute Usage of

@InitBinder relevant

Solve the problem that two entity property names are the same , When mapping, use prefixes to distinguish , For solutions, please refer to the link
more @InitBinder And @ControllerAdvice Usage of

发表回复