今天在项目中配置404页面,最开始的配置是这样的,在web.xml中加入
<error-page>
<error-code>404</error-code>
<location>/notfound.jsp</location>
</error-page>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isErrorPage="true"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
<h2>该页面不存在JSP</h2>
</body>
</html>
这样配置有两个问题:
1、当访问 http://localhost/xxxx.jsp 一个不存在的jsp时,fireFox可以到404页面,但ie由于设置友好提示没有跳到404
2、当访问 http://localhost/****.html 一个不存在的action时,虽然可以到404页,但后台有报错信息。
2010-09-14 19:10:53,093 - ERROR - Could not find action or result
There is no Action mapped for action name safdsadf. - [unknown location]
at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:186)
at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:41)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:494)
at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:422)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
******
改进方法:
1、把notfound.jsp页面大小增加到550b以上,可以解决ie友好提示跳转不到的问题。
2、在struts.xml中增加
<default-action-ref name="notfound"></default-action-ref>
<action name="notfound" class="com.opensymphony.xwork2.ActionSupport">
<result name="success" type="dispatcher">
<param name="location">notfound.jsp</param>
</result>
</action>
拦截不存在的action,这样后台就不会报错。
3、将struts.xml中的
<package name="default" namespace="/" extends="struts-default">
变成
<package name="default" extends="struts-default">
把namespace="/"去掉,这样访问任何路径不存在的action都会跳到404页面,并且后台不报错。当namespace中配置了default-action时,访问该namespace的不存在action时会到该配置的默认action;当访问不存在namespace或该namespace没有配置default-action时,会跳转到web.xml中配置的404页面