1,使用Filter的过滤功能,当用户请求的时候,根据web.xml文件里的映射,对所有定义的mapping下文件的访问都必须通过Filter。
2,Filter有3个接口,分别是:init(FilterConfig config) 完成一些初始化的工作,下面的例子中初始化了错误的转向页面。doFilter(ServletRequest request, ServletResponse response,FilterChain next)在这里完成你的过滤工作,比如字符过滤的就是设置request的编码方式.下面的例子是判断用户有没有登录。destroy()
3。java文件
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.struts.Globals;
import org.apache.struts.action.*;
public class AuthenticationFilter implements Filter {//一定要使用Filter接口
private FilterConfig filterConfig;
private String onErrorUrl;
public void init(FilterConfig config) throws ServletException {
filterConfig = config;
onErrorUrl = filterConfig.getInitParameter("onError");
if (onErrorUrl == null || "".equals(onErrorUrl)) {
onErrorUrl = "/xlogin.do";
}
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain next) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession httpSession = httpRequest.getSession();
if (httpSession.getAttribute("logon_in_editconfig") == null) {
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(
"没有登录"));
httpRequest.setAttribute(Globals.ERROR_KEY, errors);
httpRequest.getRequestDispatcher(onErrorUrl).forward(httpRequest,
httpResponse);
} else
next.doFilter(request, response);
}
public void destroy() {
}
4,在web.xml加上如下部分:
<filter>
<filter-name>Authentication</filter-name>
<filter-class>AuthenticationFilter</filter-class>//如果上面的java类放到了包下,注意加上包名
<init-param>
<param-name>onError</param-name>
<param-value>/xlogin.do</param-value>
</init-param>
</filter>
<filter-name>Authentication</filter-name>
<url-pattern>/editconfig/*</url-pattern> // editconfig/*是要过滤的文件的位置。
</filter-mapping> //表示过滤editconfig文件夹下的所内容