2009-09-17 22:11
package com.custom.data.user;
import java.io.IOException;
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.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ValidateUserLogin implements Filter {
protected FilterConfig filterConfig = null;
String checkCookies = null;
String redirectURL = null;
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResposne, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResposne;
Cookie[] cookies = request.getCookies();
UserUse userUse = new UserUse();
long userid = userUse.getUserId(cookies);
if ("".equals(userid) || userid == 0) {
response.sendRedirect(redirectURL);
return;
}
filterChain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
checkCookies = filterConfig.getInitParameter("userid");
redirectURL = filterConfig.getInitParameter("redirectURL");
}
}
web.xml
<filter> <filter-name>ValidateUserLogin</filter-name> <filter-class>com.custom.data.user.ValidateUserLogin</filter-class><!--登录错误中转地址--> <init-param> <param-name>redirectURL</param-name> <param-value>test.com</param-value> </init-param> <init-param> <param-name>checkCookies</param-name> <param-value>userid</param-value> </init-param> </filter>