本案例介绍:

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

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

黑马day14 踢人小案例的更多相关文章

  1. 监听器应用【统计网站人数、自定义session扫描器、踢人小案例】

    从第一篇已经讲解过了监听器的基本概念,以及Servlet各种的监听器.这篇博文主要讲解的是监听器的应用. 统计网站在线人数 分析 我们在网站中一般使用Session来标识某用户是否登陆了,如果登陆了, ...

  2. 机械表小案例之transform的应用

    这个小案例主要是对transform的应用. 时钟的3个表针分别是3个png图片,通过setInterval来让图片转动.时,分,秒的转动角度分别是30,6,6度. 首先,通过new Date函数获取 ...

  3. shell讲解-小案例

    shell讲解-小案例 一.文件拷贝输出检查 下面测试文件拷贝是否正常,如果cp命令并没有拷贝文件myfile到myfile.bak,则打印错误信息.注意错误信息中basename $0打印脚本名.如 ...

  4. [jQuery学习系列六]6-jQuery实际操作小案例

    前言最后在这里po上jQuery的几个小案例. Jquery例子1_占位符使用需求: 点击第一个按钮后 自动去check 后面是否有按钮没有选中, 如有则提示错误消息. <html> &l ...

  5. 02SpringMvc_springmvc快速入门小案例(XML版本)

    这篇文章中,我们要写一个入门案例,去整体了解整个SpringMVC. 先给出整个项目的结构图:

  6. React.js入门小案例

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title&g ...

  7. SqlDependency缓存数据库表小案例

    SqlDependency的简介: SqlDependency是outputcache网页缓存的一个参数,它的作用是指定缓存失效的数据库依赖项,可以具体到数据库和表. SqlDependency能解决 ...

  8. JavaScript apply函数小案例

    //回调函数1 function callback(a,b,c) { alert(a+b+c); } //回调函数2 function callback2(a,b) { alert(a+b); } / ...

  9. Session小案例------完成用户登录

    Session小案例------完成用户登录     在项目开发中,用户登陆功能再平常只是啦,当用户完毕username和password校验后.进入主界面,须要在主界面中显示用户的信息,此时用ses ...

随机推荐

  1. 【【henuacm2016级暑期训练】动态规划专题 N】Valid Sets

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 给你一棵树. 让你统计其中子树T的数量. 这个子树T要满足最大值和最小值之差小于等于d 树形DP 可以枚举点root为子树的根. 统 ...

  2. win7创建webdav

    环境 win7+iis 构筑条件 存放路径:c:\Data 访问方式:192.168.x.xxx/webdav 用户名:yx 密码:yx 搭建顺序 1.添加iis.启动->控制面板->程序 ...

  3. [CSS3] The different of Background-size between 'cover' and 'contain'

    'cover': The smaller axies of image (x axies) should match smaller axies (x axies) of container. So ...

  4. Accessibility辅助控制类

    熟悉Android开发的都知道辅助功能服务 Accessibility service.他的作用有非常多.360豌豆荚等应用市场的非root自己主动安装.微信抢红包插件.盲人辅助程序等等功能都是靠它实 ...

  5. log4j.propertie配置具体解释

    1.log4j.rootCategory=INFO, stdout , R 此句为将等级为INFO的日志信息输出到stdout和R这两个目的地,stdout和R的定义在以下的代码,能够随意起名.等级可 ...

  6. Android 启动界面的制作

    直接看实例吧 package com.example.textview; import android.app.Activity; import android.content.Intent; imp ...

  7. Codeforce 163 A. Substring and Subsequence DP

    A. Substring and Subsequence   One day Polycarpus got hold of two non-empty strings s and t, consist ...

  8. 51nod-1346: 递归

    [传送门:51nod-1346] 简要题意: 给出一个式子a[i][j]=a[i-1][j]^a[i][j-1] 给出a[1][i],a[i][1](2<=i<=131172) 有n个询问 ...

  9. Transformation in kentico

    https://docs.kentico.com/k10/developing-websites/loading-and-displaying-data-on-websites/writing-tra ...

  10. 机器翻译引擎的基本原理 ——LSTM

    机器翻译引擎的基本原理  摘自:infoq 谷歌机器翻译 Zero-shot:零次 Training:训练 Google Neural Machine Translation:谷歌神经机器翻译 我们每 ...