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