springmvc根据异常状态码转发到对应友好提示页面
解决方法:
以下就是拦截所以请求,拦截器判断系统返回的状态码转发到对应友好提示页面。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
class DefaultPageForword extends WebMvcConfigurerAdapter {
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ErrorInterceptor()).addPathPatterns(new String[]{"/**"});
super.addInterceptors(registry);
}
}
ErrorInterceptor源码如下:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class ErrorInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if (modelAndView != null) {
String noPage;
if (response.getStatus() == 500) {
modelAndView.setViewName("/500.html");
} else if (response.getStatus() == 404) {
modelAndView.setViewName("/404.html");
}
}
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}