2014-01-08 20 views
0

我使用spring MVC框架來構建我的網站並在tomcat上運行它。如何處理沒有url映射的情況?

使用http://127.0.0.1/subject/math時,它將映射到我在我的控制器中定義的math.jsp

但是,如果用戶使用我的控制器中無法處理的url,例如http://127.0.0.1/subject/math123http://127.0.0.1/otherPage,我希望該網頁將直接轉到自定義頁面,如http://127.0.0.1/default

如果我不處理的情況,就會產生一個錯誤頁HTTP Status 404和描述是The requested resource is not available.

非常感謝!

回答

1

你需要的是確定應用程序的WEB-INF/web.xml內部錯誤頁面

<error-page> 
    <!-- These are standard HTTP error codes --> 
    <error-code>404</error-code> 
    <location>/MyCustomErrorPage.jsp</location> 
</error-page> 

<!-- You can also map error pages against any exception that 
    may occur in the application --> 
<error-page> 
    <!-- Fully qualified name of the exception --> 
    <exception-type>java.lang.Exception</exception-type> 
    <location>/MyCustomErrorPage.jsp</location> 
</error-page> 

編輯

要從的errorPage.jsp轉發到其他資源的說(homePage.jsp)無更新瀏覽器中的URL,您可以使用RequestDispatcher.forward(request,response)。像在你的errorPage.jsp中一樣,添加

<% 
RequestDispatcher dispatcher = servletContext.getRequestDispatcher("/path/To/homePage.jsp"); 
dispatcher.forward(request, response); 
%> 
+0

非常感謝!有用!但我仍然有一些問題。因爲我想讓訪問錯誤鏈接的用戶直接進入主頁。你的解決方案可以讓用戶看到主頁,但url鏈接仍然是錯誤的。我該如何解決它。 – LoveTW

+0

例如,我的主頁是'http:// 127.0.0.1/default'。當用戶訪問「http:// 127.0.0.1/otherPage」時,它將看到「http:// 127.0.0.1/default」中的內容,但該url仍然是「http://127.0.0.1/otherPage」 ' – LoveTW

+2

它可以完成,雖然我會建議反對它。錯誤頁面就是錯誤頁面!它應該只包含告訴用戶您已登陸某個錯誤頁面的信息,並且您需要返回相應的頁面繼續執行該應用程序。不過,如果你想要的話,我已經更新了答案 –

相關問題