Servlet系列学习笔记11 --- 监听用户人数以及用户信息

目录

一、项目结构图

二、创建JavaBean

三、JDBC访问数据库

四、创建监听器

       4.1 监听application上下文对象,并创建专门用来存储在线用户的Map对象

       4.2 监听访问人数的变化

、创建计数器

六、创建控制器

       6.1 登录处理类

       6.2 登录注销处理类

七、JSP数据展示页面

八、结果展示


一、项目结构图

二、创建JavaBean

public class User {
	private int id;
	private String account;	//账号
	private String password;//密码
	private String name;	//姓名
	private String sex;		//性别
	private int age;		//年龄
	private long phone;		//手机号码
	private int qq;			//QQ
	private String email;	//邮箱
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getAccount() {
		return account;
	}
	public void setAccount(String account) {
		this.account = account;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public long getPhone() {
		return phone;
	}
	public void setPhone(long phone) {
		this.phone = phone;
	}
	public int getQq() {
		return qq;
	}
	public void setQq(int qq) {
		this.qq = qq;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
}

三、JDBC访问数据库

public class UserDao extends BaseDao{
	public User loginSeach(String account,String password){
		User user = new User();
		String sql = "select * from loginMsg where account = ? and password = ?";
		con = super.getConnection();
		try{
			ps = con.prepareStatement(sql);
			ps.setString(1, account);
			ps.setString(2, password);
			super.rs = ps.executeQuery();
			if(rs.next()){
				System.out.println("【查询到了】");
				sql = "select * from users where id = ?";
				ps = con.prepareStatement(sql);
				ps.setInt(1, rs.getInt("id"));
				rs = ps.executeQuery();
				if(rs.next()){
					user.setId(rs.getInt("id"));
					user.setName(rs.getString("name"));
					if(rs.getInt("sex") == 1){
						user.setSex("男");
					}else{
						user.setSex("女");
					}
					user.setAge(rs.getInt("age"));
					user.setPhone(rs.getLong("phone"));
					user.setQq(rs.getInt("qq"));
					user.setEmail(rs.getString("email"));
				}
			}else{
				user = null;
			}
		}catch(Exception e) {
			throw new RuntimeException(e);
		}finally{
			super.closeAll(rs, ps, con);
		}
		return user;
	}
}

四、创建监听器

4.1 监听application上下文对象,并创建专门用来存储在线用户的Map对象

import java.util.HashMap;
import java.util.Map;
import com.model.User;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class ContextListener implements ServletContextListener,HttpSessionListener{
	ServletContext context = null;
	Map<Integer,User> map = null;
    public void contextInitialized(ServletContextEvent arg0){
    	map = new HashMap<Integer,User>();
    	//获取Web应用的上下文对象
    	context =  arg0.getServletContext();
    	//将存储用户信息的集合对象添加到applicatiob域中
    	context.setAttribute("persons", map);
    }
    public void contextDestroyed(ServletContextEvent arg0)  {}

	public void sessionCreated(HttpSessionEvent arg0) {}
	public void sessionDestroyed(HttpSessionEvent arg0) {
		System.out.println("Session对象已被销毁");
		try{
			for(Integer key:map.keySet()){
				System.out.println(key + ":" + map.get(key).getName());
			}
		}catch(Exception e){
			System.out.println("报错");
		}
	}
}

4.2 监听访问人数的变化

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import com.service.OnlineCount;
@WebListener
public class OnlineCountListener implements HttpSessionListener {
    public void sessionCreated(HttpSessionEvent arg0)  {
    	OnlineCount.addCount();
    	System.out.println("新用户访问,人数+1");
    }
    public void sessionDestroyed(HttpSessionEvent arg0)  { 
    	OnlineCount.reduceCount();
    	System.out.println("用户结束访问,人数-1");
    }
}

五、创建计数器

public class OnlineCount {
	private static int count = 0;
	//人数增加
	public static void addCount(){
		++count;
	}
	//人数减少
	public static void reduceCount(){
		if(count > 0){
			--count;
		}
	}
	//获取当前人数
	public static int getCount(){
		return count;
	}
}

六、创建控制器

6.1 登录处理类

import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.dao.UserDao;
import com.model.User;
@WebServlet("/loginService")
public class LoginService extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		HttpSession session = request.getSession(true);
		session.setMaxInactiveInterval(60);
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		UserDao ud = new UserDao();
		User user = ud.loginSeach(account, password);
		if(user!=null){
			ServletContext context = request.getServletContext();
			Map<Integer, User> map = (Map<Integer, User>) context.getAttribute("persons");
			map.put(user.getId(), user);
			session.setAttribute("user", user);
			response.sendRedirect("index.jsp");
		}
	}
}

6.2 登录注销处理类

import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.model.User;
@WebServlet("/loginOut")
public class loginOut extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(false); //防止创建新的Session
		if(session == null){  
            response.sendRedirect("index.jsp");  
            return;  
        }
		User user = (User)session.getAttribute("user");
		//先删除上下文对象
		ServletContext context = request.getServletContext();
		Map<Integer, User> map = (Map<Integer, User>) context.getAttribute("persons");
		map.remove(user.getId());
		
		//后删除session域
        session.removeAttribute("user");
		response.sendRedirect("index.jsp");
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

七、JSP数据展示页面

<h2>在线人数:<%=OnlineCount.getCount()%></h2>
<c:choose>
	<c:when test="${user != null}">
		<h3>当前登录用户:${user.name} <span><a href="loginOut">注销</a></span></h3>
	</c:when>
	<c:otherwise>
		<h3><a href="login.jsp">登录</a></h3>
	</c:otherwise>
</c:choose>
		
<table border="1" cellspacing="0" cellpadding="10">
	<tr>
		<th>ID编号</th>
		<th>姓名</th>
		<th>性别</th>
		<th>年龄</th>
		<th>手机号码</th>
		<th>QQ</th>
		<th>邮箱</th>
	</tr>
	<c:forEach var="per" items="${persons}">
		<tr>
			<td>${per.value.id}</td>
			<td>${per.value.name}</td>
			<td>${per.value.sex}</td>
			<td>${per.value.age}</td>
			<td>${per.value.phone}</td>
			<td>${per.value.qq}</td>
			<td>${per.value.email}</td>
		</tr>
	</c:forEach>
</table>

八、结果展示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值