springmvc跳转到自定义错误页面的三种方法

本文转载自:https://blog.csdn.net/qq_37268511/article/details/103486142

有时候我们并不想跳转到系统自定义的错误页面中,那么我们需要自定义页面并且实现它的跳转

有三种方法可以实现

方法一:最简单的实现,也是最快的

在web.xml下配置如下:

<error-page>
     <error-code>404</error-code>
     <location>/WEB-INF/errors/404.jsp</location>
</error-page>

若url匹配不到则会跳转到404.jsp页面

方法二:也很简单

@RequestMapping("*")
public String test3(){
    return "404";
}

如果不能精确匹配上url,则返回404.jsp页面

方法三:重写noHandlerFound方法,实现自定义的DispatcherServlet

web.xml:

<servlet>
      <servlet-name>springmvc</servlet-name>
      <servlet-class>com.exceptionpage.test</servlet-class>
      <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-mvc.xml</param-value>
      </init-param>
    </servlet>
    <servlet-mapping>
     <servlet-name>springmvc</servlet-name>
     <url-pattern>/</url-pattern>
   </servlet-mapping>

controller类需要继承DispatcherServlet,并重写noHandlerFound方法

@Override
    protected void noHandlerFound(HttpServletRequest request,
                                  HttpServletResponse response) throws Exception {
        System.out.println("successful execute...");
        response.sendRedirect(request.getContextPath() + "/notFound");
    }

    @RequestMapping("/notFound")
    public String test2(){
        System.out.println("successful...");
        return "404";
    }

若没有匹配上url,则调用noHandlerFound方法,并且重定向到一个新的方法

新的方法中跳转到404.jsp页面

原文地址:https://www.cnblogs.com/FengZeng666/p/14643044.html