码上敲享录 > Spring框架常见问题详解分享 > springmvc根据异常状态码转发到对应友好提示页面

springmvc根据异常状态码转发到对应友好提示页面

上一章章节目录下一章 2021-07-20已有1191人阅读 评论(0)

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 {

   }

}


0

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交