同一账号,后一用户登录,前一个用户则被踢掉

原理:将已登录用户保存在数据库或者application或静态List(Map)里,

主要保存 session对象,登录账号id 等

每一个用户进行登录时去查看是否已经登陆过,

如果已登录,则取出其session然后将登陆账号id从session里移除

 

在过滤器里进行登录与否的判断

下面是一些详细步骤:

1、登录页面  login.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<h1>用户登录</h1>
<hr>
<form action="LoginServlet">
<table>
<tr><th>  用户名:</th><td><input type="text" name="username"/></td></tr>
<tr><th>   密码:</th><td> <input type="password" name="password"/></td></tr>
<tr><td></td><td> <input type="submit" value="登录"></td></tr>
</table> 
<br>
<br>
</form>
</center>

</body>
</html>

2、main_frame.jsp 登录成功后的主页面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <%  String name = (String)request.getSession().getAttribute("username");  
         %>  
        
欢迎你,<%=name%> 

<a href="ManyServlet">操作一下</a>
</body>


</html>

3、session过期(未登陆)的页面 session.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
会话已过期
</body>
<script type="text/javascript">
setTimeout(function (){
    window.location.href = "${pageContext.request.contextPath}/login.jsp";
    window.close();
}, 2000);
</script>
</html>

4、被踢下线的页面 multisession.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
你的账号在别处登录,你已被迫下线。
</body>
<script type="text/javascript">
setTimeout(function (){
    window.location.href = "<%=request.getContextPath()%>/login.jsp";
}, 2000);
</script>
</html>

 

5、进行登录的servlet

package session;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private Map<String, HttpSession> userMap = new HashMap<String, HttpSession>();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        HttpSession session = request.getSession();
        request.getSession().setAttribute("username", username);
        if(!userMap.containsKey(username))
        {
            System.out.println("新的会话ID:"+session.getId());
            userMap.put(username, session);
        }else {
            HttpSession session2 = userMap.get(username);
            if(!session2.getId().equals(session.getId()))
            {
                System.out.println("新的会话ID:"+session.getId());
                System.out.println("session已失效");
                System.out.println("已失效Id:" + session2.getId());
                 session2.removeAttribute("username");
                 session2.setAttribute("usermsg", "yes");
                userMap.put(username, session);
            }
      
        }
        String url = "main_frame.jsp";
        response.sendRedirect(url);
       
        
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

6、过滤器 SessionFilter.java

package filter;

import java.io.IOException;
import java.util.StringTokenizer;

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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.utils.SysUtils;


/**
 * Servlet Filter implementation class SessionFilter
 */
public class SessionFilter implements Filter {

    protected boolean ignore = false;                    //忽略
    protected String noFilterPath;              //不过滤的路径
    protected String sessionTimeoutPage;        //Session过期转向的页面
    /**
     * Default constructor. 
     */
    public SessionFilter() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see Filter#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        // place your code here

        // pass the request along the filter chain
        
       if(this.ignore)
    {
        chain.doFilter(request, response);
        return;
    }
        
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp= (HttpServletResponse) response;
        HttpSession session = req.getSession();
        
        String username = (String) session.getAttribute("username");
        boolean isLogin = username!=null;
        
       
        if(!isLogin)
        {
            String servletPath = req.getServletPath(); //当前服务端路径
            if(!isMatchPath(noFilterPath, servletPath)) //如果不匹配则转到Login页面
            {
                String url = req.getRequestURI() + (req.getQueryString() != null ? "?" + req.getQueryString() : "");
                    if(session.getAttribute("usermsg")!= null&&!session.getAttribute("usermsg").equals("") )
                    {
                        resp.sendRedirect(req.getContextPath()+"/multisession.jsp");
                        return;
                    }
                    resp.sendRedirect(req.getContextPath()+"/session.jsp");
                    System.out.println("Session is timeout. 地址为:" + url);
                    return;
              
            }
            
            
        }
        chain.doFilter(request, response);
    }

    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
        this.ignore = "true".equalsIgnoreCase(fConfig.getInitParameter("ignore"));
        this.noFilterPath = fConfig.getInitParameter("noFilterPath");
    }
    /**
     * 是否匹配过虑路径
     *
     * @param filterPath 过滤路径
     * @param path       访问的地址
     * @return 匹配返回true,否则返回false
     */
    public boolean isMatchPath(String filterPath, String path)
    {
    /*    StringTokenizer token = new StringTokenizer(filterPath, path);
        while(token.hasMoreTokens())
        {
            String patter = SysUtils.trim(token.nextToken());
            boolean match = SysUtils.wildcardMatch(patter, path);
            if(match)
            {
              return true;  
            }
        }
        return false;*/
        if(filterPath.contains(path))
        {
            return true;
        }
        return false;
    }

}

7、进行额外业务servlet    ManyServlet.java

package session;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ManyServlet
 */
public class ManyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ManyServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("业务逻辑哈哈");
        String url = "haha.jsp";
        response.sendRedirect(url);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

 

对应的jsp haha.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
嘿,你好。
</body>
</html>

web.xml 中fileter的配置

  <filter>
    <filter-name>SessionFilter</filter-name>
    <filter-class>filter.SessionFilter</filter-class>
    <init-param>
      <param-name>ignore</param-name>
      <param-value>false</param-value>
    </init-param>
    <init-param>
      <param-name>sessionTimeoutPage</param-name>
      <param-value>/error.jsp</param-value>
    </init-param>
     <init-param>
            <param-name>noFilterPath</param-name>
            <param-value>/login.jsp, /LoginServlet, /session.jsp, /multisession.jsp, /index.jsp
            </param-value>
        </init-param>
  </filter>
  <filter-mapping>
    <filter-name>SessionFilter</filter-name>
    <url-pattern>*.jsp</url-pattern>
  </filter-mapping>
  <filter-mapping>
    <filter-name>SessionFilter</filter-name>
    <url-pattern>*</url-pattern>
  </filter-mapping>

 

posted @ 2016-01-29 19:51  羊皮纸月亮  阅读(1436)  评论(0编辑  收藏  举报