1.HttpSessionBindingListener
实体类
package com.etime.enetity;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
//此处需要实现HttpSessionBindingListener接口,并重新里面方法
public class Student implements HttpSessionBindingListener{
private String name;
private int age;
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public void valueBound(HttpSessionBindingEvent event) {
System.out.println("该"+event.getValue()+"学生被session绑定了");
}
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
System.out.println("该"+event.getValue()+"学生被session解绑了");
}
}
<%@ page import="com.etime.enetity.Student" %><%--
Created by IntelliJ IDEA.
User: xx
Date: 2023/9/2
Time: 20:01
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
<%
Student student1 = new Student("张三", 23);
Student student2 = new Student("李四", 21);
Student student3 = new Student("zh", 21);
session.setAttribute("stu1",student1);
session.setAttribute("stu2",student2);
session.setAttribute("stu1",student3);
session.removeAttribute("stu1");
session.removeAttribute("stu2");
%>
2.. HttpSessionActivationListener
package com.etime.enetity;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;
import java.io.Serializable;
//实现HttpSessionActivationListener和Serializable接口
public class Teacher implements HttpSessionActivationListener, Serializable {
private String name;
private int age;
public Teacher() {
}
public Teacher(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Teacher{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public void sessionWillPassivate(HttpSessionEvent se) {
System.out.println("钝化了");
}
@Override
public void sessionDidActivate(HttpSessionEvent se) {
System.out.println("活化了");
}
}
<%@ page import="com.etime.enetity.Teacher" %><%--
Created by IntelliJ IDEA.
User: xx
Date: 2023/9/2
Time: 20:20
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
<%--测试钝化,访问此页面,然后关闭服务器,查看是否保存在文件中--%>
<%
Teacher teacher = new Teacher("张三", 23);
session.setAttribute("teacher",teacher);
%>
<%--
Created by IntelliJ IDEA.
User: xx
Date: 2023/9/2
Time: 20:20
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
<%--测试活化,再次重启服务其然后直接访问此页面,观察数据是否还存在--%>
${teacher}
思路分析:通过ServletContextListener监听,当Web应用上下文启动时,在ServletContext中添 加一个List集合,用来准备存放在线的用户名;然后,可以通过HttpSessionAttributeListener监 听器,当用户登录成功,把用户名设置到Session中时,同时将用户名存放到ServletContext中的 List列表中;最后通过HttpSessionListener监听,当用户注销会话时,将用户名从应用上下文范围 中的List列表中删除。
登陆界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
主页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
$Title$
$END$退出登陆
欢迎您,${sessionScope.username}
现在访问本网站的用户有:
${str}
servlet
@WebServlet(name = "LoginServlet", value = "/LoginServlet.ser")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
boolean flag=true;
if (flag){
//登陆成功
HttpSession session = request.getSession();
System.out.println(username);
session.setAttribute("username",username);
request.getRequestDispatcher("index.jsp").forward(request,response);
}else {
//登陆失败
}
}
}
退出登陆
@WebServlet(name = "OutLoginServlet", value = "/OutLoginServlet.ser")
public class OutLoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.invalidate();
response.sendRedirect("login.jsp");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
监听器
@WebListener
public class UserLoginListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener {
ServletContext servletContext = null;
@Override
public void contextInitialized(ServletContextEvent sce) {
//服务器启动时就创建一个集合,存储访问本网站的用户
List list = new LinkedList<>();
//获取ServletContext对象
servletContext = sce.getServletContext();
//将集合放到ServletContext对象中
servletContext.setAttribute("list", list);
}
@Override
public void attributeAdded(HttpSessionBindingEvent se) {
//用户登陆时将用户名放入集合中
//获取session对象
HttpSession session = se.getSession();
//获取KEY
if ("username".equals(se.getName())) {
//放入session中名字为username的才存入集合中
//获取用户名
String username = (String) se.getValue();
//String username = (String)session.getAttribute("username");
//获取集合
List list =(List) servletContext.getAttribute("list");
//将数据存入集合中
list.add(username);
//最后再将集合放回去
servletContext.setAttribute("list",list);
}
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
//用户退出时,就是session对象的销毁,将退出用户从集合中移出去
//获取session对象
HttpSession session = se.getSession();
String username =(String) session.getAttribute("username");
//从集合中移除掉
List list =(List) servletContext.getAttribute("list");
list.remove(username);
servletContext.setAttribute("list",list);
}
}
过滤器---解决中文乱码问题-和未登录不能访问主页面
@WebFilter("*.ser")
public class ChainFilter implements javax.servlet.Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("init");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//处理中文乱码
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charset=utf-8");
//放行
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
System.out.println("destroy");
}
}
@WebFilter("/index.jsp")
public class indexFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
HttpSession session = request.getSession();
Object username = session.getAttribute("username");
if (username==null){
response.sendRedirect("login.jsp");
}else {
filterChain.doFilter(servletRequest, servletResponse);
}
}
}