项目中有这样一种需求:一个用户登录时,判断这个用户名是否已被别人登陆,若有,则踢出前面登陆的用户
public class TestAction extends GenericAction {
ActionServlet servlet = this.getServlet();
HttpSession session = request.getSession();
String userId = request.getParameter("userId");
ServletContext servletContext = servlet.getServletContext();
HttpSession oldSession = (HttpSession) servletContext
.getAttribute(userId);
boolean isFirstLogin = (oldSession == null);
// 若这个老session的Id等于新的session的Id,则表明这个用户还是以前用户
boolean isSameLogin = (oldSession != null)
&& oldSession.getId().equals(session.getId());//这一点比较重要,很多人会漏掉
//设置第一次登陆或者剔出以前登陆的用户
if (isFirstLogin || !isSameLogin) {
servletContext.setAttribute(userId, session);
}
}
若是在每次业务操作中都要判断这个逻辑,则把上面的实现代码放到filter中,当然上面的功能也可以同在数据库中存贮sessionId来判断。
注意:上面的代码缺少真正的权限,也就是userId与password的判断,可以自行加上