本案例介绍:

使用监听器来实现踢人小案例,仅仅有管理员才有踢人的功能。

1.搭建开发环境,导入本案例须要的jar包。以及一个准备好的数据库工具类:提供数据源的方法...当中我已经在数据库中加入了三个用户

a:123

b:123

admin:123

package com.itheima.util;
import java.sql.Connection;
import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class DataSourceUtil {
private static DataSource source = new ComboPooledDataSource();
private DataSourceUtil() {
}
public static DataSource getSource(){
return source;
}
public static Connection getConn(){
try {
return source.getConnection();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}

我使用的是c3po的配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/day14? generateSimpleParameterMetadata=true</property>
<property name="user">root</property>
<property name="password">169500</property>
</default-config>
</c3p0-config>

2.建立主页页面,假设没有登陆就提供登陆的超链接。假设登陆成功就欢迎用户,同一时候提供注销的超链接,和用户列表在线用户的超链接。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> <title></title> <meta http-equiv=" pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0"> </head> <body>
<c:if test="${sessionScope.user==null }">
欢迎游客...<a href="${pageContext.request.contextPath }/login.jsp">请登录</a>
</c:if>
<c:if test="${sessionScope.user!=null }">
欢迎${sessionScope.user.name}<a href="${pageContext.request.contextPath }/servlet/LogoutServlet">注销</a><br>
<a href="${pageContext.request.contextPath }/userList.jsp">在线用户列表</a>
</c:if>
</body>
</html>

3.开发登陆login.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv=" pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<h1>登录页面</h1><hr>
<form action="${pageContext.request.contextPath }/servlet/LoginServlet" method="post">
username:<input type="text" name="name"/><br>
密码:<input type="password" name="password"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>

执行演示:

4.开发jsp的action的LoginServlet:

步骤:

(1).获取请求參数,我使用的是post提交方式

(2).验证用户和password和数据库中的是不是一直,假设不一致就提示用户信息不存在,假设一致,就把user加入到session域中...

(3).请求转发到主页,欢迎用户...

package cn.itheima.web;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap; 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 org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler; import cn.itheima.domain.User; import com.itheima.util.DataSourceUtil; public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//1.获取请求參数
String name = request.getParameter("name");
String password = request.getParameter("password");
//2.验证密码和数据库中的是否一致
User user=null;
try {
QueryRunner runner=new QueryRunner(DataSourceUtil.getSource());
String sql="select * from user where name=? and password=? ";
user=runner.query(sql, new BeanHandler<User>(User.class),name,password);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}
//3.检验
if(user==null){
response.getWriter().write("username不存在!");
}else{
//将还有一个同名同密码的用户挤下去
ServletContext context = this.getServletContext();
HashMap<User, HttpSession> usermap = (HashMap<User, HttpSession>) context.getAttribute("usermap");
HttpSession session = usermap.get(user);
if(session!=null){
session.invalidate();
}
request.getSession().setAttribute("user", user);
response.sendRedirect(request.getContextPath()+"/index.jsp");
}
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }

5.注销的功能:LogoutServlet

把session中的user干掉就可以

package cn.itheima.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class LogoutServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if(request.getSession(false)!=null){
request.getSession().invalidate();
}
//重定向到主页
response.sendRedirect(request.getContextPath()+"/index.jsp");
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }

6.为了实现踢人的功能:而每一个人登陆的session仅仅是自己的。为了拿到全部用户的session。因此当应用载入完成的时候就在ServletContext域中放一个usermap对象...

我们使用监听器:监听器的配置我就不多说了,在web.xml文件里配置就可以...

package cn.itheima.listener;

import java.util.HashMap;
import java.util.Map; import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.http.HttpSession; import cn.itheima.domain.User; public class ServletContextListener implements javax.servlet.ServletContextListener{ public void contextInitialized(ServletContextEvent sce) {
ServletContext context = sce.getServletContext();
context.setAttribute("usermap", new HashMap<User, HttpSession>());
System.out.println("监听了!..........");
}
public void contextDestroyed(ServletContextEvent sce) {
} }

7.当用户在session域中放一个user用户的时候我们须要user这个javaBean自己探測到因此须要使用HttpSessionBindingListener接口:

登陆的时候就加入session到application域中。注销的时候就移除..重写hashcode和equal方法为了是username和password同样我们视为同一个对象。

package cn.itheima.domain;

import java.io.Serializable;
import java.util.HashMap; import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
public class User implements Serializable,HttpSessionBindingListener{
private int id;
private String name;
private String role;
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
//当session中被绑定了对象的时候就往域对象中加入
public void valueBound(HttpSessionBindingEvent event) {
HttpSession session = event.getSession();
ServletContext context = session.getServletContext();
HashMap<User, HttpSession> map=(HashMap<User, HttpSession>) context.getAttribute("usermap");
map.put(this, session);
}
//注销的时候就移除
public void valueUnbound(HttpSessionBindingEvent event) {
HttpSession session = event.getSession();
ServletContext context = session.getServletContext();
HashMap<User, HttpSession> map=(HashMap<User, HttpSession>) context.getAttribute("usermap");
map.remove(this);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
} }

8.在LoginServlet中我们登陆的时候将同username和password的挤下线...见第6步骤

9.编写用户列表:

在这里推断用户是不是admin假设是admin就提供踢人的功能。

这里主要是遍历application域中的在线的用户..

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> <title></title> <meta http-equiv=" pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0"> </head>
<h1>用户列表</h1><hr>
<c:forEach items="${applicationScope.usermap}" var="entry">
${entry.key.name }
<c:if test="${sessionScope.user.role=='admin'}">
<a href="${pageContext.request.contextPath }/servlet/KickServlet?id=${entry.key.id }">踢人</a>
</c:if>
<br>
</c:forEach>
</html>

10.编写踢人的servlet,把id带到servlet:

通过id查询出用户然后将其从usermap干掉就可以...

package cn.itheima.web;

import java.io.IOException;

import java.sql.SQLException;
import java.util.HashMap;
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 org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler; import com.itheima.util.DataSourceUtil; import cn.itheima.domain.User; public class KickServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1.获取id
String id = request.getParameter("id");
//2.依据id查询用户
String sql="select * from user where id= ? ";
User user=null;
QueryRunner runner=new QueryRunner(DataSourceUtil.getSource());
try {
user=runner.query(sql, new BeanHandler<User>(User.class),id);
} catch (SQLException e) {
e.printStackTrace();
}
ServletContext context = this.getServletContext();
HashMap<User, HttpSession> map=(HashMap<User, HttpSession>) context.getAttribute("usermap");
HttpSession session = map.get(user);
if(session!=null)
session.invalidate();
response.sendRedirect(request.getContextPath()+"/userList.jsp");
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }

11.执行结果分析:

踢人a

最新文章

  1. Redis命令拾遗四(集合类型)—包含简单搜索筛选商品设计实例。
  2. 一鼓作气 博客--第四篇 note4
  3. POSIX正则表达式
  4. colormap
  5. freeglut第一步
  6. Interface Comparator
  7. MATLAB-ginput函数问题
  8. 分布式算法(一致性Hash算法)
  9. 【HDU3065】 病毒侵袭持续中(AC自动机)
  10. Xmanager连接CentOS的远程桌面
  11. Request.url用法
  12. 在 CentOS 上安装 Tomcat7
  13. Swift 与 JSON 数据 浅析
  14. 通过HPS控制FPGA端的GPIO
  15. node错误中间件处理 express类 带有路由操作
  16. VMware5.5-虚拟机的迁移和资源分配
  17. python获取系统开机时间
  18. java动态代理_aop
  19. OS X 配置 Apache
  20. centos6.5 mqtt安装

热门文章

  1. VUE使用中踩过的坑
  2. MyBatis学习总结(4)——解决字段名与实体类属性名不相同的冲突
  3. Ural 1004 Sightseeing Trip
  4. java ee服务器/应用服务器的理解
  5. 2014百度之星资格赛—— Xor Sum(01字典树)
  6. DICOM医学图像处理:fo-dicom网络传输之 C-Echo and C-Store
  7. iOS 常见小问题
  8. bzoj4519: [Cqoi2016]不同的最小割(分治最小割)
  9. kibana智能检索发送多次_msearch —— 配置index pattern,同时设置时间段,就知道到底是在哪些索引里去查找数据了
  10. 极客时间 Mysql实战45讲 07讲行锁功过:怎么减少行锁对性能的影响笔记 极客时间