踢人小案例

本案例介绍:

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

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">
    	用户名:<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).验证用户和密码和数据库中的是不是一直,如果不一致就提示用户信息不存在,如果一致,就把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("用户名不存在!");
		}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方法为了是用户名和密码相同我们视为同一个对象。

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中我们登陆的时候将同用户名和密码的挤下线...见第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





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值