talk is cheap, show me the code, as follows:
import org.springframework.ui.Model; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.context.request.NativeWebRequest; /** * 1. The global configuration for the controller can be placed in the same location through the @ControllerAdvice annotation. * 2. The methods of classes annotated with @Controller can be annotated with @ExceptionHandler, @InitBinder, and @ModelAttribute. * 3. The @ControllerAdvice annotation will apply to all controller methods annotated with @RequestMapping. * 4. @ExceptionHandler: used to handle exceptions in the controller globally. * 5. @InitBinder: used to set the WebDataBinder, which is used to automatically bind the foreground request parameters to the Model. * 6. @ModelAttribute: The original function is to bind the key-value pair to the Model. Here, the global @RequestMapping can obtain the key-value pair set here * * @author zx * @date 2017-03-10 */ @ControllerAdvice public class GlobalControllerInterceptor { @ModelAttribute //Apply to all @RequestMapping annotation methods //Add the key-value pair to the global here, and any method annotated with @RequestMapping can get this key-value pair public void addUser(Model model) { model.addAttribute("msg", "Add the key-value pair to the global here, any method annotated with @RequestMapping can get this key-value pair"); } @InitBinder //Applies to all @RequestMapping annotated methods, initializes the data binder before its execution //Used to set the WebDataBinder, used to automatically bind the foreground request parameters to the Model. public void initBinder(WebDataBinder binder) { } @ExceptionHandler(Exception.class) //Apply to all @RequestMapping annotated methods and execute when it throws an Exception //Define global exception handling, value attribute can filter interception conditions, intercept all Exceptions here public String processUnauthenticatedException(NativeWebRequest request, Exception e) { return "error"; //return a logical view name } }
Project address: https://github.com/zhangxia1030/spring-boot-example