public class LoginFilter implements Filter {
private static List<String> exclude_uris = new ArrayList<String>(0);
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
String uri = request.getRequestURI();
// 获取请求URL
String path = uri
+ (request.getQueryString() != null ? "?"
+ request.getQueryString() : "");
// 获取上下文对象
String context = request.getContextPath();
HttpSession session = request.getSession();
// 获取session的sid
String sid = session.toString().substring(
session.toString().lastIndexOf("@") + 1);
// 获取服务器全局对象
ServletContext application = session.getServletContext();
// 获取全局对象中的 上线用户列表
HashMap<String, String> onlines = (HashMap<String, String>) application
.getAttribute("onlines");
if (onlines == null) {
onlines = new HashMap<String, String>(0);
}
String loginid = null;
if (session.getAttribute("loginid") != null) {
loginid = session.getAttribute("loginid").toString();
}
Object flag = session.getAttribute("islogin");
if (flag == null || !flag.toString().equals("1")) {
// 未登录
if (exclude_uris.contains(path.replace(context + "/", ""))
|| path.indexOf(context + "/imgs/") != -1
|| path.indexOf(context + "/css/") != -1
|| path.indexOf(context + "/js/") != -1) {
// 请求URL在不拦截列表,不拦截
chain.doFilter(request, response);
} else {
// 拦截请求,转发网页到login.jsp
session.setAttribute("error", "请登录!");
response.sendRedirect(context + "/login.jsp");
}
} else {
// 已经登录
if (!onlines.containsKey(loginid)
|| !sid.equals(onlines.get(loginid))) {
// 登录账号已经在先前登录
if (!exclude_uris.contains(path.replace(context + "/", ""))
&& path.indexOf(context + "/imgs/") == -1
&& path.indexOf(context + "/css/") == -1
&& path.indexOf(context + "/js/") == -1) {
// 之前登录的相同账号被踢出
session.setAttribute("error", "您的账号在其他地方登录了!");
response.sendRedirect(context + "/login.jsp");
} else {
chain.doFilter(request, response);
}
} else {
chain.doFilter(request, response);
}
}
}
@Override
public void init(FilterConfig fConfig) throws ServletException {
String excludes = fConfig.getInitParameter("excludes");
String[] excludes_arr = excludes.split(",");
for (String e : excludes_arr) {
exclude_uris.add(e);
}
}
}
基于Filter的简单登录过滤器
最新推荐文章于 2020-06-21 15:57:51 发布