这篇文章主要为大家展示了“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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。