1. 过滤的路径要有统一的可以表示的路径,以方便模块化过滤
例如:用户模块:/user/*,信息模块:/info/*
2. 过滤器要有能排除不过滤路径的功能;
3. 实现相关的业务需要;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import com.dbdata.constant.DBDataConstants;
public class LoginFilter implements Filter {
private static final Logger logger = Logger.getLogger(LoginFilter.class);
public LoginFilter() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
HttpServletResponse resp = (HttpServletResponse) response;
String url = req.getRequestURI();
logger.info("url:" + url);
//不需要过滤的链接
List<String> excludeLinks = new ArrayList<String>();
excludeLinks.add("/dbdatamanage/admin/login/valid");
if (!excludeLinks.contains(url)) {
String user_name = (String) session.getAttribute(DBDataConstants.USER_NAME);
String user_id = (String) session.getAttribute(DBDataConstants.USER_ID);
logger.info("user_name:" + user_name);
logger.info("user_id:" + user_id);
if (StringUtils.isEmpty(user_name) || StringUtils.isEmpty(user_id)) {
resp.sendRedirect(req.getContextPath() + "/jhub/login.jsp");
return;
}
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}