例如统计已登录的人数
1.使User对象继承 HttpSessionBindingListener 接口,实现其中两个方法,如下:
package com.hy.bean;
import java.io.Serializable;
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 static final long serialVersionUID = 1L;
private int id;
private String username;
private String password;
private String email;
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(int id, String username, String password, String email) {
super();
this.id = id;
this.username = username;
this.password = password;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + "]";
}
//向Session中添加User对象被调用
@Override
public void valueBound(HttpSessionBindingEvent event) {
System.out.println("user对象被添加到Session域中了");
//获取Session对象
HttpSession session = event.getSession();
//获取ServletContext对象
ServletContext application = session.getServletContext();
//从application域中获取当前在线人数
Integer count = (Integer)application.getAttribute("count");
if(null==count) {
//证明之前还没有人上线,这是第一人
application.setAttribute("count", 1);
}else {
application.setAttribute("count", count+1);
}
}
//USer对象从ssion域中移除时调用
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
//获取Session对象
HttpSession session = event.getSession();
//获取ServletContext对象
ServletContext application = session.getServletContext();
//从application域中获取当前在线人数
Integer count = (Integer)application.getAttribute("count");
application.setAttribute("count", count-1);
}
}
2.前端登录后展示的页面:main.jsp 添加一行统计人数的
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<h1>欢迎<span style="color : blue">${sessionScope.user.username}</span>登陆</h1><br>
<a href="${pageContext.request.contextPath}/LogOutServlet">注销</a><br>
<h2>当前在线人数:<span style="color : red">${applicationScope.count}</span>人</h2><br>
<c:if test="${empty requestScope.users}">
<h1>没有任何用户!</h1>
</c:if>
<c:if test="${! empty requestScope.users }">
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<th>ID</th>
<th>用户名</th>
<th>密码</th>
<th>邮箱</th>
<th colspan="2">操作</th>
</tr>
<c:forEach items="${requestScope.users}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.password}</td>
<td>${user.email}</td>
<td><a href="#">编辑</a></td>
<td><a href="#">删除</a></td>
</tr>
</c:forEach>
</table>
</c:if>
</center>
</body>
</html>
3.登录页面 :login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<base href="http://localhost:8080/Web_Ex/">
<style type="text/css">
body {
background-color: pink
}
</style>
<!-- javaScript编写位置 -->
<script type="text/javascript" src="script/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
//给文本框绑定focus事件
$("#userName").focus(function(){
//将显示错误信息的span标签中的文本置空
$("#msgSpan").html("<font color='green'>获得焦点后增加的文字</font>");
});
//给登录按钮绑定单击事件
$("#sub").click(function(){
var username = $("#userName").val();
//判断用户名是否为空
if(username==""){
alert("用户名不能为空!");
return false;
}
});
});
</script>
</head>
<body>
<h1>欢迎来到登录页面</h1><br/>
<form action="Login" method="post">
用户名称:<input type="text" name="userName" id="userName"><span id ="msgSpan"style="color:red">${requestScope.msg}</span><br/>
密 码:<input type="password"
name="password"><br /> <input type="submit" id="sub" value="登录">
</form>
</body>
</html>
4.相关Servlet:
LoginServlet.java
package com.hy.servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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.hy.bean.User;
import com.hy.dao.UserDao;
import com.hy.dao.impl.UserDaoImpl;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取用户名和密码
String username=request.getParameter("userName");
String password=request.getParameter("password");
//创建UserDao对象
UserDao userDao = new UserDaoImpl();
User user = userDao.checkUserNameAndPassword(username, password);
if(user!=null) {
//用户名和密码正确,重定向到登录成功页面
HttpSession session = request.getSession();
session.setAttribute("user", user);
response.sendRedirect(request.getContextPath()+"/GetUserServlet");
}else {
request.setAttribute("msg", "用户名或密码不正确!");
RequestDispatcher requestDispatcher=request.getRequestDispatcher("/pages/login.jsp");
requestDispatcher.forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
GetUserServlet.java
package com.hy.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hy.bean.User;
import com.hy.dao.UserDao;
import com.hy.dao.impl.UserDaoImpl;
public class GetUserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public GetUserServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UserDao userDao = new UserDaoImpl();
List<User> list =userDao.getUsers();
request.setAttribute("users", list);
//转发到主页面
request.getRequestDispatcher("/pages/main.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
5.web.xml的配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Web_Ex</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>Login</display-name>
<servlet-name>Login</servlet-name>
<servlet-class>com.hy.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>RegistServlet</display-name>
<servlet-name>RegistServlet</servlet-name>
<servlet-class>com.hy.servlet.RegistServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegistServlet</servlet-name>
<url-pattern>/RegistServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>AjaxServlet</display-name>
<servlet-name>AjaxServlet</servlet-name>
<servlet-class>com.hy.servlet.AjaxServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AjaxServlet</servlet-name>
<url-pattern>/AjaxServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>CheckUserNameServlet</display-name>
<servlet-name>CheckUserNameServlet</servlet-name>
<servlet-class>com.hy.servlet.CheckUserNameServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CheckUserNameServlet</servlet-name>
<url-pattern>/CheckUserNameServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>GetUserServlet</display-name>
<servlet-name>GetUserServlet</servlet-name>
<servlet-class>com.hy.servlet.GetUserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetUserServlet</servlet-name>
<url-pattern>/GetUserServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>CreateCookie</display-name>
<servlet-name>CreateCookie</servlet-name>
<servlet-class>com.hy.servlet.CreateCookie</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CreateCookie</servlet-name>
<url-pattern>/CreateCookie</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>LogOutServlet</display-name>
<servlet-name>LogOutServlet</servlet-name>
<servlet-class>com.hy.servlet.LogOutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogOutServlet</servlet-name>
<url-pattern>/LogOutServlet</url-pattern>
</servlet-mapping>
<filter>
<display-name>LoginFilter</display-name>
<filter-name>LoginFilter</filter-name>
<filter-class>com.hy.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/GetUserServlet</url-pattern>
</filter-mapping>
</web-app>
6.显示结果:
(1)先进入登录页面,登录之后会显示已经有1人;
(2)再换一个浏览器登录,登陆之后结果显示有2人;