spring boot 作為微服務的便捷框架,在錯誤頁面處理上也有一些新的處理,不同于之前的spring mvc 500的頁面處理是比較簡單的,用java config或者xml的形式,定義如下的bean即可
1
2
3
4
5
6
7
8
9
10
11
|
< bean class = "org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" > < property name = "exceptionMappings" > < props > < prop key = "org.apache.shiro.authz.UnauthenticatedException" >pages/403</ prop > < prop key = "org.apache.shiro.authz.UnauthorizedException" >pages/403</ prop > < prop key = "org.apache.shiro.authc.LockedAccountException" >pages/locked</ prop > < prop key = "java.lang.Throwable" >pages/500</ prop > </ props > </ property > </ bean > |
404就比較特殊了,有2種方法可以參考:
1. 先設置dispatcherServlet
1
2
3
4
5
6
7
|
@Bean public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) { ServletRegistrationBean registration = new ServletRegistrationBean( dispatcherServlet); dispatcherServlet.setThrowExceptionIfNoHandlerFound( true ); return registration; } |
再增加處理錯誤頁面的handler,加上@ControllerAdvice 注解
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@ControllerAdvice public class GlobalControllerExceptionHandler { public static final String DEFAULT_ERROR_VIEW = "pages/404" ; @ExceptionHandler (value = NoHandlerFoundException. class ) public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception { ModelAndView mav = new ModelAndView(); mav.addObject( "exception" , e); mav.addObject( "url" , req.getRequestURL()); mav.setViewName(DEFAULT_ERROR_VIEW); return mav; } } |
不過上面這種處理方法,會造成對js,css等資源的過濾,最好使用第二種方法
2. 集成ErrorController
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
@Controller public class MainsiteErrorController implements ErrorController { private static final String ERROR_PATH = "/error" ; @RequestMapping (value=ERROR_PATH) public String handleError(){ return "pages/404" ; } @Override public String getErrorPath() { // TODO Auto-generated method stub return ERROR_PATH; } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/projectarchitect/article/details/42463471