本文以springboot+thmyleaf+shiro為列。
1.官方默認的視圖路徑如下
2.而默認異常頁面路徑即為:src/main/resources/templates/error;結構如下:
src/ +- main/ +- java/ | + <source code> +- resources/ +- public/ +- error/ | +- 404.html
| +- 403.html
| +- 500.html
+- <other public assets>
3.自定義異常視圖處理器:
import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authz.AuthorizationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** *異常視圖處理器 * * @author * @date 2019/4/17 */ public class ExcetionViewResolver implements HandlerExceptionResolver { private static final Logger log= LoggerFactory.getLogger(ExcetionViewResolver.class); @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ModelAndView modelAndView = new ModelAndView(); if ((ex instanceof AuthenticationException) ) { modelAndView.setViewName("/error/403"); modelAndView.getModel().put("msg","登錄失敗!"); } else if(ex instanceof AuthorizationException) { modelAndView.setViewName("/error/403"); modelAndView.getModel().put("msg","沒有權限!"); }else{ modelAndView.setViewName("/error/500"); modelAndView.getModel().put("msg","發生未知異常!"); } return modelAndView; } }
4.注入自定義處理器; 類似於注冊filter、servlet等組件,參考 https://blog.csdn.net/king_is_everyone/article/details/53116744
/** * @author * @date 2018/9/23 */ @Controller @SpringBootApplication public class BootAllRun { public static void main(String[] args) { SpringApplication.run(BootAllRun.class,args); } /** * 添加自定義異常-視圖 處理器 * * @author * @date 2019/4/17 15:56 * @param * @return [返回值說明] */ @Bean public WebMvcConfigurer webMvcConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers){ exceptionResolvers.add(new ExcetionViewResolver()); } }; } }
5.權限方法
6.運行結果:
處理前:
處理后:
最后:官網也提供了,自定義錯誤頁面解決樣例。但處理關鍵以HttpStatus status值做划分,異常時則是統一的處理結果(500頁面)。本文細化到具體異常匹配處理結果 (官網也提供了依據@ExceptionHandler 處理的思路
)。
總結:SpringMVC框架是圍繞着處理所有的HTTP請求和響應的DispatcherServlet的設計。DispatcherServlet控制整個處理流程(包括本文的異常處理DispatcherServlet的handlerExceptionResolvers屬性關聯),再通過springboot的相關組件注入即可達到相關流程控制。