开发web项目,一般必须先登录成功才能进入主页,但在浏览器里直接输入主页地址,同样可以直接进入,毫无安全性可言,所以需要登录过滤器来过滤未登录用户到登录页面
package com.*.util.filter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
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;
import com.*.common.model.User;
import com.*.util.config.ProperConfigUtil;
public class LoginFilter extends HttpServlet implements Filter {
private static final long serialVersionUID = 1L;
/**
* 排除的表达式
*/
@SuppressWarnings("serial")
private static final Set<Pattern> excludeSet = new HashSet<Pattern>() {
{
// 用户模块部分
// add(Pattern.compile("/user_.+\\.do"));
add(Pattern.compile("/login.do"));
add(Pattern.compile("/user.do"));
}
};
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
String sessionId = httpRequest.getParameter("JSESSIONID");
// boolean blen = httpRequest.isRequestedSessionIdFromURL();
HttpSession session = httpRequest.getSession();
sessionId = session.getId();
@SuppressWarnings("unchecked")
Map<String, HttpSession> sessions = (Map<String, HttpSession>) httpRequest
.getSession().getServletContext().getAttribute("sessions");
String webroot = ProperConfigUtil.getConfigByKey("webroot");
if(webroot == null){
webroot = session.getServletContext().getRealPath("");
ProperConfigUtil.setConfig("webroot", webroot);
}
User user = null;
if (sessionId != null && !"".equals(sessionId)) {
if (sessions.containsKey(sessionId)) {
user = (User) sessions.get(sessionId).getAttribute("USER");
} else {
httpResponse.sendRedirect(httpRequest.getContextPath()
+ "/login.do?method=goLogin");
return;
}
}
if(user == null) {
user = (User) session.getAttribute("USER");
}
String code = httpRequest.getMethod();
String url = httpRequest.getRequestURI();
if (code == null) {
httpResponse.sendRedirect(httpRequest.getContextPath()
+ "/login.do?method=goLogin");
return;
}
for (Pattern excludePattern : excludeSet) {
if (excludePattern.matcher(url).find()) {
chain.doFilter(request, response);
return;
}
}
if (user == null || "".equals(user.getUserName())) {
// 判断获取的路径不为空且不是访问登录页面或执行登录操作时跳转
if (url != null && !url.equals("") && code.indexOf("Login") < 0
&& code.indexOf("login") < 0) {
httpResponse.sendRedirect(httpRequest.getContextPath()
+ "/login.do?method=goLogin");
return;
}
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}