① 创建ErrorInterceptor类,implements HandlerInterceptor
package com.tenement.utils.interceptor; import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.springframework.stereotype.Controller;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView; /** * 自定义拦截器 * * @author wk * @create 2018/02/27 */@Controllerpublic class ErrorInterceptor implements HandlerInterceptor { private static final Log logger = LogFactory.getLog(ErrorInterceptor.class); /* * preHandle方法 * * */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.info("【-MyInterceptor1,在请求处理之前进行调用(controller方法调用之前)-】"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { logger.info("【-MyInterceptor1,请求处理之后进行调用,但是在视图被渲染之前(controller方法调用之后)-】"); if(response.getStatus()==500){ modelAndView.setViewName("/view/base/errorpage/500.html"); /* * setViewName(String viewName); * 为此ModelAndView设置视图名称,由DispatcherServlet通过ViewResolver解析。 将覆盖任何预先存在的视图名称或视图。 */ }else if(response.getStatus()==404){ modelAndView.setViewName("/view/base/errorpage/404.html"); } } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { logger.info("【-MyInterceptor1,在整个请求结束之后被调用,也就是在DispatcherServlet渲染了对应的视图之后执行(主要用于资源清理工作)-】"); } }
② 创建MyWebAppConfigurer extends WebMvcConfigurerAdapter
package com.tenement.utils.interceptor; import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configurationpublic class MyWebAppConfigurer extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new ErrorInterceptor()).addPathPatterns("/**"); super.addInterceptors(registry); } /* * 对页面的静态资源也会进行拦截,导致异常 * */}