您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“spring mvc中如何處理異常”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“spring mvc中如何處理異常”這篇文章吧。
spring mvc中的404:
1.mappedHandler找不到
response.sendError(HttpServletResponse.SC_NOT_FOUND);
spring mvc異常機制
1.mappedHandler找不到 并且throwExceptionIfNoHandlerFound設定為true
throwExceptionIfNoHandlerFound
source:
if (this.throwExceptionIfNoHandlerFound) { throw new NoHandlerFoundException(request.getMethod(), getRequestUri(request), new ServletServerHttpRequest(request).getHeaders()); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); }
config:
web.xml的配置Dispatcher的此參數為true
<init-param> <param-name>throwExceptionIfNoHandlerFound</param-name> <param-value>true</param-value> </init-param>
2.判斷返回視圖層之前是否發生了異常,主要有兩種HandlerExceptionResolver、ModelAndViewDefiningException
3.如沒有異常,則進行視圖渲染
通過viewResolver找出相應的view,進行具體的模板渲染
通過不同的View實現AbstractView的renderMergedOutputModel方法
Exception if there's a problem rendering the view
如果ViewResolver匹配不到對應的View,則拋出ServletException
ServletException:if view is missing or cannot be resolved
spring mvc 異常處理
1.HandlerExceptionResolver
只能處理請求過程中拋出的異常
不處理異常處理本身所拋出的異常和視圖解析過程中拋出的異常
2.@ControllerAdvice的@ExceptionHandler注解
3.1和2只能處理view之前的異常,如果是視圖層渲染異常,需要另行處理
一.利用filter,捕獲除了1和2之外的異常
public class ErrorHandlerFilter implements Filter { ErrorHandler errorHandler; @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { try { filterChain.doFilter(request, response); } catch (Exception ex) { // call ErrorHandler and dispatch to error jsp String errorMessage = errorHandler.handle(request, response, ex); request.setAttribute("errorMessage", errorMessage); request.getRequestDispatcher("/WEB-INF/jsp/error/dispatch-error.jsp").forward(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { errorHandler = (ErrorHandler) WebApplicationContextUtils .getRequiredWebApplicationContext(filterConfig.getServletContext()) .getBean("defaultErrorHandler"); } // ... }
二.從寫dispatchServlet再doservice時候捕獲異常
public class DispatcherServletHandler extends DispatcherServlet { private static final String ERROR = "error"; private static final String VIEW_ERROR_PAGE = "/WEB-INF/views/error/view-error.jsp"; @Override protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception { try{ super.doService(request, response); } catch(Exception ex) { request.setAttribute(ERROR, ex); request.getRequestDispatcher(VIEW_ERROR_PAGE).forward(request, response); } } }
以上是“spring mvc中如何處理異常”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。