webxml里添加filter配置信息
<filter>
<filtername>Authentication</filtername>
<filterclass>
limaswebfiltersAuthenticationFilter
</filterclass>
<initparam>
<paramname>onError</paramname>
<paramvalue>/pages/indexjsp</paramvalue>
</initparam>
</filter>
<filtermapping>
<filtername>Authentication</filtername>
<urlpattern>/protect/*</urlpattern>
</filtermapping>
<filterclass>定义使用limaswebfiltersAuthenticationFilter类执行过滤Action
<initparam>当验证失败后Forward到/pages/indexjsp
<filtermapping>只有当地址包括/protect/时运行filter类
实现limaswebfiltersAuthenticationFilter
package limaswebfilters;
import javaioIOException;
import javaxservletRequestDispatcher;
import javaxservletServletException;
import javaxservlethttp*;
import javaxservletFilter;import javaxservletFilterChain;
import javaxservletFilterConfig;
import limaswebbeanUserBean;
import javaxservletServletRequest;
import javaxservletServletResponse;import orgapachestrutsGlobals;
import orgapachestrutsaction*;
import nstantsConstants;
/**
* Filter implementation for user authentication必须实现Filter接口
* @author tyrone * @version $Id: AuthenticationFilterjavav
*/public class AuthenticationFilter implements Filter{
/**
* filterConfig will store the reference of FilterConfig
*/ private FilterConfig filterConfig;
private String onErrorUrl;
/**
* store the reference of the FilterConfig
* @param config FilterConfig object
* @throws ServletException
*/ public void init(FilterConfig config) throws ServletException
{//获得验证失败forward地址
filterConfig = config;
onErrorUrl=filterConfiggetInitParameter(onError);
if (onErrorUrl==null || equals(onErrorUrl)){
onErrorUrl=/pages/indexjsp;
}
}
/**
* User Authentication isdone If User is authenticated successful then
* control is transferred to logon URI
* @param ServletRequest Request
* @param ServletRequest Response
* @param FilterChain Filter Chain
* @throws ServletExceptionIOException
*/ public void doFilter(ServletRequest request ServletResponse response FilterChain next)
throws IOException ServletException
{
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse=(HttpServletResponse)response;
// Current session
HttpSession httpSession = ();
//Session里是否有用户信息
if ((ConstantsUSER_KEY) == null)
{
ActionErrors errors=new ActionErrors();
errorsadd(ActionErrorsGLOBAL_ERROR
new ActionError(error authentication));
(GlobalsERROR_KEYerrors);
//没有验证失败forward到/pages/indexjsp
(onErrorUrl)forward(httpRequesthttpResponse);
}else//成果过滤Action结束
nextdoFilter(requestresponse);
}
/**
* destroy() method is called by the servlet container
*/ public void destroy()
{
}
}