没有url映射时如何处理这种情况?

时间:2014-01-08 06:45:59

标签: spring tomcat spring-mvc

我使用spring MVC框架来构建我的网站并在tomcat上运行它。

使用http://127.0.0.1/subject/math时,它会映射到我在控制器中定义的math.jsp

但是如果用户使用我未在我的控制器中处理的网址,例如http://127.0.0.1/subject/math123http://127.0.0.1/otherPage,我希望网页可以直接转到自定义网页,例如{{1 }}

如果我不处理这种情况,则会出现错误页面http://127.0.0.1/default,说明为HTTP Status 404

非常感谢!

1 个答案:

答案 0 :(得分: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);
%>