springmvc跳轉到自定義404頁面的三種方法


有時候我們並不想跳轉到系統自定義的錯誤頁面中,那么我們需要自定義頁面並且實現它的跳轉

有三種方法可以實現

方法一:最簡單的實現,也是最快的

在<web-app>節點下配置

代碼如下:

1 <error-page>
2     <error-code>404</error-code>
3     <location>/WEB-INF/errors/404.jsp</location>
4   </error-page>

若url匹配不到則會跳轉到404.jsp頁面

方法二:也很簡單

1 @RequestMapping("*")
2     public String test3(){
3         return "404";
4     }

如果不能精確匹配上url,則返回404.jsp頁面

方法三:重寫noHandlerFound方法,實現自定義的DispatcherServlet

web.xml

 1 <servlet>
 2     <servlet-name>springmvc</servlet-name>
 3     <servlet-class>com.exceptionpage.test</servlet-class>
 4     <init-param>
 5       <param-name>contextConfigLocation</param-name>
 6       <param-value>classpath:spring-mvc.xml</param-value>
 7     </init-param>
 8   </servlet>
 9   <servlet-mapping>
10     <servlet-name>springmvc</servlet-name>
11     <url-pattern>/</url-pattern>
12   </servlet-mapping>

 

controller類需要繼承DispatcherServlet,並重寫noHandlerFound方法

 1 @Override
 2     protected void noHandlerFound(HttpServletRequest request,
 3                                   HttpServletResponse response) throws Exception {
 4         System.out.println("successful execute...");
 5         response.sendRedirect(request.getContextPath() + "/notFound");
 6     }
 7 
 8     @RequestMapping("/notFound")
 9     public String test2(){
10           System.out.println("successful...");
11           return "404";
12     }

若沒有匹配上url,則調用noHandlerFound方法,並且重定向到一個新的方法

新的方法中跳轉到404.jsp頁面

<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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM