监听器综合案例

61 篇文章 0 订阅

本案例实现一个登录功能,管理员登录时,可以踢用户下线。


案例的bug及解决方案:


附上代码:

MyServletContextListener.java

package com.listener;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;

import com.bean.User;

public class MyServletContextListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		ServletContext context=arg0.getServletContext();
		Map<User,HttpSession>map=new HashMap<User,HttpSession>();
		context.setAttribute("map",map);
	}

}
MySessionListener.java

package com.listener;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.bean.User;

public class MySessionListener implements HttpSessionAttributeListener,HttpSessionListener {

	@Override
	public void attributeAdded(HttpSessionBindingEvent arg0) {
		HttpSession session=arg0.getSession();
		ServletContext context=session.getServletContext();
		Map<User,HttpSession>map=(Map<User, HttpSession>) context.getAttribute("map");
		map.put((User) session.getAttribute(arg0.getName()),session);
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent arg0) {		
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void sessionCreated(HttpSessionEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
		HttpSession session=arg0.getSession();
		User u=(User) session.getAttribute("user");
		Map<User,HttpSession>map=(Map<User, HttpSession>) session.getServletContext().getAttribute("map");
		map.remove(u);
	}

}
CheckUserExist.java

package com.servlet;

import java.util.ArrayList;
import java.util.List;

import com.bean.User;

public class CheckUserExist {
	
	private static List<User>users=null;

	public static void init()	
	{
		users=new ArrayList<User>();
		User u=new User();
		u.setId(1);
		u.setUsername("zhangsan");
		u.setPassword("123");
		users.add(u);
		User u1=new User();
		u1.setId(2);
		u1.setUsername("lisi");
		u1.setPassword("123");
		users.add(u1);		
		User u2=new User();
		u2.setId(3);
		u2.setUsername("wangwu");
		u2.setPassword("123");
		users.add(u2);
		User u3=new User();
		u3.setId(4);
		u3.setUsername("admin");
		u3.setPassword("123");
		users.add(u3);	
	}

	
	public static User findUser(String username,String password){
		if(users==null){
			init();
		}
		for(int i=0;i<users.size();++i){
			if(users.get(i).getUsername().equals(username)&&users.get(i).getPassword().equals(password))
			{
				return users.get(i);
			}
		}
		return null;
	}
	
}

DaoLogin.java

package com.servlet;

import java.io.IOException;
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;

import com.bean.User;

public class DaoLogin extends HttpServlet {
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		User user=CheckUserExist.findUser(username, password);
		if(user!=null){
			request.getSession().invalidate();//若是用户在同一个浏览器登录,则应把过去的登录状态移除掉,即把Session销毁
			Map<User,HttpSession>map=(Map<User, HttpSession>) getServletContext().getAttribute("map");
			for(User u:map.keySet())
			{
				if(u.getUsername().equals(username))
				{
					map.get(u).invalidate();//若是用户已经登录,则把过去登录的用户移除,确保一个帐号同一时间最多一个人登录
					break;
				}
			} 
		
			request.getSession().setAttribute("user", user);
			response.sendRedirect("/ListenerProject/list.jsp");
			return ;
		}
		else{
			request.setAttribute("msg", "用户名或密码错误");   
			request.getRequestDispatcher("/login.jsp").forward(request, response);  
			return ;	
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}



KickServlet.java

package com.servlet;

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

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

import com.bean.User;

public class KickServlet extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String id=request.getParameter("id");
		Map<User,HttpSession>map=(Map<User, HttpSession>) request.getSession().getServletContext().getAttribute("map");
		for(Entry e:map.entrySet())
		{
			User u=(User)e.getKey();
			if(u.getId()==Integer.parseInt(id))
			{
				map.get(u).invalidate();
				break;
			}
		}
		response.sendRedirect("/ListenerProject/list.jsp");
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {


	}

}
login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>

  <body>
  <div style="color:red;">${msg}</div>
    <form action="/ListenerProject/servlet/DaoLogin" method="post">
    用户名:<input type="text" name="username">  <br/>
    密码:<input type="password" name="password"> <br/> 
    <input type="submit" name="登录">
    </form>
  </body>
</html>

list.jsp

<%@ page language="java" import="java.util.*,com.bean.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'list.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">

  </head>
  
  <body>
<h1> 当前用户  ${user.username}<br/></h1>
在线用户:<br/> 
 <c:forEach items="${applicationScope.map}" var="entry">
 ${entry.key.username}     
 <c:if test="${'admin' != entry.key.username  && user.username == 'admin'}">
  <a href="/ListenerProject/servlet/KickServlet?id=${entry.key.id}">踢下去</a>
  </c:if>
  <br/>
 </c:forEach>
 
  </body>
</html>
























评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值