捕捉 404/500 错误,自定义Tomcat错误页面

当服务器出现404、500错误时候希望能够给用户友好的现实界面
只需要在项目的web.xml中添加一些配置

Java代码
  1.   
  2.   
  3. <!-- 400错误 -->   
  4. <error-page>   
  5. <error-code>400</error-code>   
  6. <location>/error.jsp</location>   
  7. </error-page>   
  8. <!-- 404 页面不存在错误 -->   
  9. <error-page>   
  10. <error-code>404</error-code>   
  11. <location>/error.jsp</location>   
  12. </error-page>   
  13. <!-- 500 服务器内部错误 -->   
  14. <error-page>   
  15. <error-code>500</error-code>   
  16. <location>/error.jsp</location>   
  17. </error-page>   
  18. <!-- java.lang.Exception异常错误,依据这个标记可定义多个类似错误提示 -->   
  19. <error-page>   
  20. <exception-type>java.lang.Exception</exception-type>   
  21. <location>/error.jsp</location>   
  22. </error-page>   
  23. <!-- java.lang.NullPointerException异常错误,依据这个标记可定义多个类似错误提示 -->   
  24. <error-page>   
  25. <exception-type>java.lang.NullPointerException </exception-type>   
  26. <location>/error.jsp</location>   
  27. </error-page>   
  28.   
  29. <error-page>   
  30. <exception-type>javax.servlet.ServletException</exception-type>   
  31. <location>/error.jsp</location>   
  32. </error-page> 

为了获得很好的用户感受,是不应当向用户暴露404这样的页面的,
问题的出发点是我在Struts2中定义错误页面,
在Struts2中是这样定义的:

Xml代码
  1. <default-action-ref name="pagenotfound"></default-action-ref>  
  2.   
  3. <action name="pagenotfound">  
  4.             <result>/pagenotfound.html</result>  
  5. </action>  
<default-action-ref name="pagenotfound"></default-action-ref>

<action name="pagenotfound">
			<result>/pagenotfound.html</result>
</action>



这就是说在访问action是.如果没有找到action就访问这个页面,
但是我如果我不用.do或者.action的样式,而直接使用.jsp或者.html的方式来访问页面的请,struts就不会处理了.结果是404错误依然出现.
现在已经不是struts的处理范围了,那么这应当是应用的处理范围,经查证,在工程的web.xml中可以设置自定义错误页面,设置如下:

Xml代码
  1. <error-page>  
  2.         <error-code>404</error-code>  
  3.         <location>/pagenotfound.html</location>  
  4. </error-page>  
<error-page>
		<error-code>404</error-code>
		<location>/pagenotfound.html</location>
</error-page>



现在再访问该该工程下面一个不存在的页面,将跳转到自定义的pagenotfound页面,这样,struts中的那个default-action-ref 配置是可以去掉的了.因为404交给tomcat处理了

转载于:https://my.oschina.net/usenrong/blog/197847

猜你喜欢

转载自blog.csdn.net/weixin_34336526/article/details/92028961