JAVA Filter和Listener實現簡單的用戶單一登陸和用戶超時退出,鎖定

自己寫的一點簡單的代碼,僅供學習交流,廢話不多說直接上代碼,

1.實現一個HttpSessionListener 用來監聽session

public class LoginListener implements HttpSessionListener {

private Logger logger = LoggerFactory.getLogger(LoginListener.class);

public static HashMap<String, String> userMap = new HashMap<String, String>();

public static HashMap<String, HttpSession> sessionMap = new HashMap<String, HttpSession>();

// 使session失效,並移除map
public void destroyed(String username, HttpServletRequest request) {
HttpSession session = request.getSession();
String sessionid = userMap.get(username);
if(sessionMap.containsKey(sessionid)){
synchronized (this) {
sessionMap.get(sessionid).invalidate();
sessionMap.remove(sessionid);
userMap.remove(username);
}
}else{
userMap.remove(username);
}
}
// 將session信息存入map
public void created(Object o,String username, HttpServletRequest request) {
HttpSession session = request.getSession();
//logger.info("創建的sessionID:"+session.getId());
userMap.put(username, session.getId());
sessionMap.put(session.getId(), session);
session.setMaxInactiveInterval(60*120);
Map<String, Object> user =(Map<String, Object>)o;
}
@Override
public void sessionCreated(HttpSessionEvent arg0) {
}
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
HttpSession session = arg0.getSession();
String sessionid = session.getId();
logger.info("session shixiaol"+session.getId());
sessionMap.remove(sessionid);
}

}

2.在實現一個過濾器,過濾session,實現無session強制退出。

public void doFilter(ServletRequest request, ServletResponse response,
                 FilterChain chain) throws IOException, ServletException {
           HttpServletRequest httpreq = (HttpServletRequest) request;
           HttpServletResponse httpres = (HttpServletResponse) response;
           String redirectPath = httpreq.getContextPath()
                   + config.getInitParameter("redirectPath");
           String uri = httpreq.getRequestURI();
          // logger.info(" uri is "+uri);
           //不攔截login,驗證碼
           if(uri.endsWith("login.do")|| uri.endsWith("image.do") || uri.endsWith("per.do")  ){
           chain.doFilter(request, response);
           return;
           }
           Object user= httpreq.getSession().getAttribute("user");
           if(user==null){
            logger.info("未登錄");
            request.setAttribute("msg", "登陸用戶已超時,請重新登陸!");
            httpreq.getRequestDispatcher("/login.jsp").forward(httpreq, response);
           } else {
                 chain.doFilter(request, response);
           }

     }

3.Spring mvc 實現以一個Contorller LoginController來做控制層

public ModelAndView login(HttpServletRequest request){
ApiResponse api = new ApiResponse();
ModelAndView modelAndView = new ModelAndView();
try {
HttpSession session = request.getSession();  
String message;
String username =request.getParameter("username");
String password =request.getParameter("password");
Map map = new HashMap();
map.put("userId", username);
map.put("passwd", Md5Util.MD5(password));
Object o = permissionService.getBaseDao().getOneEntity("sys_user.exits", map);
Map<String, Object> user = null;
if(o!=null){
String sessionid = LoginListener.userMap.get(username);   
logger.info("sessionid:"+sessionid);
LoginListener userSession = new LoginListener();  
if(sessionid != null&&!sessionid.equals("")){  
    //註銷在線用戶,如果session id 相同,不銷燬.
    if(!sessionid.equals(session.getId())){
    if(session.isNew()){
    userSession.created(o,username, request);  
    }else{
    userSession.destroyed(username, request);
    userSession.created(o, username, request);
    }
    }
}else{  
    userSession.created(o,username, request);  
}
user =(Map<String, Object>)o;
/*request.getSession().setAttribute("user", user);
request.getSession().setAttribute("userName", (String)user.get("userName"));*/
}else{
message ="用戶名或密碼錯誤";
modelAndView.setViewName("/login");
modelAndView.addObject("msg", message);
return modelAndView;
}
}catch (Exception e) {
api.setApi_code(1);
e.printStackTrace();
}
return modelAndView;

}

4.實現一個login.jsp from 表單提交完成用戶登錄功能.

<form id="loginForm" name="loginForm" action="<%=path %>/login/login" method="post"  >
   <div id="warp">   
   <table class="login">
   <tr>
    <td colspan="2"><div class="error" >用戶或密碼不能爲空! </div></td>
   </tr>
    <tr>
    <td>用戶名:</td>
    <td><input  type="text" name="username" id="username"/></td>
    </tr>
    <tr>
    <td>密碼:</td>
    <td><input  type="password" name="password" id="password" /></td>
    </tr>
    <tr>
     <td></td>
     <td><input type="button" class="loginBT" value="" οnclick="logonCheck()"/></td>
    </tr>
   </table>    
   </div>
    <div class="clear"> </div>

 </form>

未經博主允許,請勿轉載https://blog.csdn.net/qq_35238963/article/details/80283631

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章