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);
}
}
}
转载于:https://blog.51cto.com/xinzhilian/2054184