第一步:一定确保 登陆的文件不可以在过滤的目录中;
例:
![](http://static.oschina.net/uploads/space/2012/0813/222048_7rHy_162199.jpg)
haople为需要过滤的目录;login.html为提交登陆的文件;
第二步:新建一个servlet 类(这里命名为LoginFilter)并实现Filter 接口;
其代码:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@SuppressWarnings("serial")
public class LoginFilter extends HttpServlet implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req=(HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
HttpSession ses=req.getSession();
String condition=req.getRequestURI(); //当前请求的路径
String path = req.getContextPath()+"/login.html";
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path; //未通过滤时跳转的路径
//System.out.print("f dsfsd"+ses.getAttribute("username"));
if(null == ses.getAttribute("loginName") || "".equals(ses.getAttribute("loginName"))){
if(condition.contains("adminlogin.do")){ //提交的路径为adminlogin.do不过滤
chain.doFilter(request, response);
}
else{
res.sendRedirect(basePath);
}
}
else{
chain.doFilter(request, response);
}
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
/**
* Constructor of the object.
*/
public LoginFilter() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void init() throws ServletException {
// Put your code here
}
}
第三步: 配置web.xml 文件
配置内容:
<filter>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<filter-name> LoginFilter</filter-name>
<filter-class>com.haopeng.servlet.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name> LoginFilter</filter-name>
<url-pattern> /haople/*</url-pattern> <!-- 此处为过滤haople目录下的所有文件 -->
</filter-mapping>
<filter>