一个很简单的demo来演示一个账号只能同时被一个人使用(Java实现)

大家在登陆qq的时候,电脑上登陆了qq,如果另一台机器上也登陆该qq账号,那么之前的qq账号会被挤下去。

我们现在用web的方式来做一个非常简单的演示。

先简单的说一下功能吧,

用户只有一个User,这个entity设置成账号为hello,密码world


这样做为了简化不到数据库里面去查用户的账号信息。

首先,我们看一看我们的web.xml


[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"  
  3.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"  
  5.          version="3.1">  
  6.   
  7.     <listener>  
  8.         <listener-class>SessionListener</listener-class>  
  9.     </listener>  
  10. </web-app>  
web.xml里面就配置了一个HttpSessionListener


类SessionListener的实现如下

[html]  view plain  copy
  1. import javax.servlet.http.HttpSession;  
  2. import javax.servlet.http.HttpSessionEvent;  
  3. import javax.servlet.http.HttpSessionListener;  
  4. import java.util.HashMap;  
  5.   
  6. /**  
  7.  * Created by HuLuo on 2016/8/20.  
  8.  */  
  9. public class SessionListener implements HttpSessionListener  
  10. {  
  11.     /**  
  12.      * 该HashMap以用户名-HttpSession对象存储一个账号只能被一个人登陆的信息。  
  13.      */  
  14.     public static HashMap<String,HttpSession> sessionMap = new HashMap<String,HttpSession>();  
  15.   
  16.     @Override  
  17.     public void sessionCreated(HttpSessionEvent httpSessionEvent)  
  18.     {  
  19.         HttpSession session = httpSessionEvent.getSession();  
  20.     }  
  21.   
  22.     @Override  
  23.     public void sessionDestroyed(HttpSessionEvent httpSessionEvent)  
  24.     {  
  25.   
  26.         HttpSession session = httpSessionEvent.getSession();  
  27.   
  28.         delSession( session );  
  29.     }  
  30.   
  31.     public static synchronized void delSession(HttpSession session)  
  32.     {  
  33.         if(session != null)  
  34.         {  
  35.   
  36.             // 删除单一登录中记录的变量  
  37.             if(session.getAttribute( "users" ) != null)  
  38.             {  
  39.                 User user = (User) session.getAttribute( "users" );  
  40.                 SessionListener.sessionMap.remove( user.getUsername() );  
  41.             }  
  42.         }  
  43.     }  
  44.   
  45. }  

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

这个HashMap是用来存储用户的登陆信息,一个账户同时只能被一个人使用。


接着是demo的首页面,里面很简单,只有一个超链接,让其访问到 

${pageContext.request.contextPath}/login


这边笔者也是简化的不能再简化了,直接连账户名密码也不用填。直接登陆上。。。。。。

再来我们看LoginServlet.java ------------------------------>判断这个账号是否被其他人登陆的逻辑判断


代码如下

[java]  view plain  copy
  1. import javax.servlet.ServletException;  
  2. import javax.servlet.annotation.WebServlet;  
  3. import javax.servlet.http.HttpServlet;  
  4. import javax.servlet.http.HttpServletRequest;  
  5. import javax.servlet.http.HttpServletResponse;  
  6. import javax.servlet.http.HttpSession;  
  7. import java.io.IOException;  
  8.   
  9. /** 
  10.  * Created by HuLuo on 2016/8/20. 
  11.  */  
  12. @WebServlet(urlPatterns = "/login")  
  13. public class LoginServlet extends HttpServlet  
  14. {  
  15.     @Override  
  16.     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException  
  17.     {  
  18.         User user = new User();  
  19.         HttpSession session = req.getSession();  
  20.         /** 
  21.          * 该账号已经被登陆 
  22.          */  
  23.         if(null != SessionListener.sessionMap.get( user.getUsername() ))  
  24.         {  
  25.             /** 
  26.              * 将已经登陆的信息拿掉,将新的用户登录信息放进去 
  27.              */  
  28.             ForceLogoutUtils.forceUserLogout( user.getUsername() );  
  29.   
  30.             SessionListener.sessionMap.put( user.getUsername(), session );  
  31.         }  
  32.         /** 
  33.          * 该账号未被登陆 
  34.          */  
  35.         else  
  36.         {  
  37.             SessionListener.sessionMap.put( user.getUsername(), session );  
  38.         }  
  39.         session.setAttribute( "users", user );  
  40.         req.getRequestDispatcher( "result.jsp" ).forward( req,resp );  
  41.     }  
  42. }  

然后我们接着讲ForceLogoutUtils.java

这个类呢是用来,当发现账号已经被人登陆了,就将这个已经登陆上的人的Session从SessionListener.java中的HashMap里给拿到,并且移除在此HashMap中的记录

并将session  invalidate掉。



[html]  view plain  copy
  1. import javax.servlet.http.HttpSession;  
  2. import java.util.Enumeration;  
  3.   
  4. /**  
  5.  * Created by HuLuo on 2016/8/20.  
  6.  */  
  7. public class ForceLogoutUtils  
  8. {  
  9.     public static void forceUserLogout(String username)  
  10.     {  
  11.         if(SessionListener.sessionMap.get( username ) != null)  
  12.         {  
  13.             HttpSession session = SessionListener.sessionMap.get( username );  
  14.   
  15.             SessionListener.sessionMap.remove( username );  
  16.   
  17.             Enumeration e = session.getAttributeNames();  
  18.   
  19.             while(e.hasMoreElements())  
  20.             {  
  21.                 String sessionName = (String) e.nextElement();  
  22.   
  23.                 session.removeAttribute( sessionName );  
  24.             }  
  25.   
  26.             session.invalidate();  
  27.         }  
  28.     }  
  29. }  
在LoginServlet.java处理的结果出来之后,跳转到一个result.jsp这个页面


页面内容也是只有一个超链接。检查自己是否被踢下

<%--           以下的超链接用于检验自己登陆的被踢下,被踢下了返回到index.jsp页面        --%>
    <a href="${pageContext.request.contextPath}/check">检验</a>

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2016/8/20
  Time: 11:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>


<body>


<%--           以下的超链接用于检验自己登陆的被踢下,被踢下了返回到index.jsp页面        --%>
    <a href="${pageContext.request.contextPath}/check">检验</a>
</body>
</html>


如果被踢下返回到index.jsp页面,如果没有被踢下,就继续留在result.jsp

是否被踢下


最后我们来看CheckServlet.java里面的逻辑判断


[java]  view plain  copy
  1. import javax.servlet.ServletException;  
  2. import javax.servlet.annotation.WebServlet;  
  3. import javax.servlet.http.HttpServlet;  
  4. import javax.servlet.http.HttpServletRequest;  
  5. import javax.servlet.http.HttpServletResponse;  
  6. import java.io.IOException;  
  7.   
  8. /** 
  9.  * Created by HuLuo on 2016/8/20. 
  10.  */  
  11. @WebServlet(urlPatterns = "/check")  
  12. public class CheckServlet extends HttpServlet  
  13. {  
  14.     @Override  
  15.     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException  
  16.     {  
  17.         User user = (User) req.getSession().getAttribute( "users" );  
  18.   
  19.         if(null == user)  
  20.         {  
  21.   
  22.             resp.sendRedirect( "index.jsp" );  
  23.         }  
  24.         else  
  25.         {  
  26.             resp.sendRedirect( "result.jsp" );  
  27.         }  
  28.   
  29.     }  
  30. }  

判断从Session中拿到,是否有users信息,如果有继续留在result.jsp页面,如果没有重定向到index.jsp
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值