一个简单的登录过滤器
public class LoginFilter
implements Filter
{
public static final String LOGIN_URI_CONF = "login_uri";
public static final String LOGIN_FORWARD_URI_CONF = "login_forward_uri";
public static final String MUST_IN_SESSION_CONF = "must_in_session";
public static final String NEED_NOT_LOGIN_URIS_CONF = "need_not_login_uris";
public String loginUri;
public String forwardLoginUri;
public String mustInSession;
public List<String> needNotLoginUris;
public void init(FilterConfig filterConfig)
throws ServletException
{
loginUri = filterConfig.getInitParameter(LOGIN_URI_CONF);
forwardLoginUri = filterConfig.getInitParameter(LOGIN_FORWARD_URI_CONF);
mustInSession = filterConfig.getInitParameter(MUST_IN_SESSION_CONF);
needNotLoginUris = new ArrayList<String>();
String needNotLoginUrisStr = filterConfig.getInitParameter(NEED_NOT_LOGIN_URIS_CONF);
if (needNotLoginUrisStr != null && needNotLoginUrisStr.trim().length() != 0) {
needNotLoginUrisStr = needNotLoginUrisStr.replaceAll(System.getProperty("line.separator"),
"");// Replace all line breaks
String[] uriArray = needNotLoginUrisStr.split(",");
for (String uri : uriArray) {
needNotLoginUris.add(uri.trim());
}
}
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException
{
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
// System.out.println(">>>>>Request URI= " + httpRequest.getRequestURI());
//如果是请求登录,或者是登录前页面,或者是请求其他不需要登录页面,则通过
//如果是请求资源文件如.css,.jpg等,也通过
String reqURI = httpRequest.getRequestURI();
if (reqURI.indexOf(loginUri) != -1 ||
reqURI.indexOf(forwardLoginUri) != -1 ||
containsInList(needNotLoginUris, httpRequest.getRequestURI()) ||
reqURI.indexOf(".action") == -1) {
filterChain.doFilter(request, response);
}
else {
//如不存在对应本请求的session也不创建
HttpSession session = httpRequest.getSession(false);
if (session == null || session.getAttribute(mustInSession) == null) {
//未登录,但请求需要登录的URI,则转向登录页面
httpResponse.sendRedirect(forwardLoginUri);
}
else {
filterChain.doFilter(request, response);
}
}
}
public void destroy()
{
}
private boolean containsInList(List<String> uris, String uri)
{
for (String u : uris) {
if (uri.indexOf(u) != -1) {
return true;
}
}
return false;
}
}
web.xml配置如下
<filter> <filter-name>LoginFilter</filter-name> <filter-class>com.ceno.mcps.portal.action.LoginFilter</filter-class> <init-param> <param-name>login_uri</param-name> <param-value>/portal-www/loginWww.action</param-value> </init-param> <init-param> <param-name>login_forward_uri</param-name> <param-value>/portal-www/preView.action</param-value> </init-param> <init-param> <param-name>need_not_login_uris</param-name> <param-value> /portal-www/listCategoryByServiceType.action, /portal-www/listAllContent.action, </param-value> </init-param> <init-param> <param-name>must_in_session</param-name> <param-value>userId</param-value> </init-param> </filter>