package com.lfg.filter;
import javax.servlet.*;
import java.io.IOException;
public class FirstFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("filter init");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("doFilter");
//放行
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
System.out.println("filter destroy");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--注册过滤器-->
<filter>
<filter-name>FirstFilter</filter-name>
<filter-class>com.lfg.filter.FirstFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>FirstFilter</filter-name>
<!--配置过滤路径-->
<url-pattern>/index.jsp</url-pattern>
</filter-mapping>
</web-app>
package com.lfg.filter;
import javax.servlet.*;
import java.io.IOException;
@WebFilter("/index.jsp")
public class FirstFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("filter init");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("doFilter");
//放行
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
System.out.println("filter destroy");
}
}
格式 | 描述 |
---|---|
/* | 过滤所有的服务器端资源 |
*.jsp | 过滤所有以.jsp结尾的服务器端资源 |
/studentServlet | 只能过滤studentServlet这个路径的服务器端资源 |
生命周期 | 描述 |
---|---|
init() | 调用init() 方法初始化实例,在服务器启动时只调用一次 |
doFilter() | 每次访问请求,如果被访问的请求符合过滤条件都会调用doFilter() 方法进行真正的过滤处理 |
destroy() | 停止服务器调用destroy() 方法,销毁实例,释放资源,只执行一次 |
<filter>
<filter-name>FirstFilter</filter-name>
<filter-class>com.lfg.filter.FirstFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>FirstFilter</filter-name>
<!--配置过滤路径-->
<url-pattern>/index.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>FirstFilter</filter-name>
<!--配置过滤路径-->
<url-pattern>/studentServlet</url-pattern>
</filter-mapping>
@WebFilter(filterName = "FirstFilter",urlPatterns = {"/index.jsp","/studentServlet"})
<filter-mapping>
<filter-name>FirstFilter</filter-name>
<!--配置过滤路径-->
<url-pattern>/test.jsp</url-pattern>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
@WebFilter(filterName = "FirstFilter",urlPatterns = "/test.jsp",dispatcherTypes = DispatcherType.FORWARD)
package com.lfg.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter("/*")
public class EncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("filter 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("filter destroy");
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="loginServlet" method="post">
账号:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
package com.lfg.servlet;
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 java.io.IOException;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
//默认登录成功
boolean res = true;
if (res) {
HttpSession session = req.getSession();
session.setAttribute("username",username);
resp.sendRedirect("index.jsp");
} else {
resp.sendRedirect("login.jsp");
}
}
}
package com.lfg.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/index.jsp")
public class LoginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)servletRequest;
HttpServletResponse resp = (HttpServletResponse)servletResponse;
HttpSession session = req.getSession();
Object username = session.getAttribute("username");
if (username == null) {
resp.sendRedirect("login.jsp");
} else {
filterChain.doFilter(req, resp);
}
}
@Override
public void destroy() {
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
欢迎您${sessionScope.username}
</body>
</html>
依据(域对象) | ServletContext域 | HttpSession域 | ServletRequest域 |
---|---|---|---|
创建与销毁 | ServletContextListener | HttpSessionListener | ServletRequestListener |
属性变化 | ServletContextAttributeListener | HttpSessionAttributeListener | ServletRequestAttributeListener |
绑定到HttpSession域中某个对象的状态 | HttpSessionBindingListener HttpSessionActivationListener |
(1)定义一个普通类实现监听器接口;
(2)重写监听器接口方法;
(3)注册监听器:配置 web.xml 或 @WebListener注解;
package com.lfg.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ApplicationListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("ServletContext init");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("ServletContext Destroyed");
}
}
<listener>
<listener-class>com.lfg.listener.ApplicationListener</listener-class>
</listener>
当tomcat服务器开启时执行被创建的方法contextInitialized,服务器被关闭时执行被销毁的方法contextDestroyed
package com.lfg.listener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener
public class SessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("session create");
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("session destroy");
}
}
@WebListener
测试创建:
创建一个jsp页面test.jsp
直接访问index.jsp页面,由于session是jsp的内置对象,意味着在访问index.jsp页面时创建了session对象,因此会触发监听器的创建方法
测试销毁:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
session.invalidate();
%>
</body>
</html>
package com.lfg.listener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class RequestListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("request destroy");
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
System.out.println("request init");
}
}
@WebListener
运行JSP文件即可
监听器 | 描述 |
---|---|
ServletContextAttributeListener | 监听ServletContext中属性的变化 |
HttpSessionAttributeListener | 监听HttpSession中属性的变化 |
ServletRequestAttributeListener | 监听ServletRequest中属性的变化 |
操作 | 描述 |
---|---|
attributeAdded | 监听属性添加-当数据范围对象没有该属性,第一次添加时会自动触发调用执行 |
attributeRemoved | 监听属性移除- 从一个数据范围对象删除一个已经存在的属性时会自动触发执行 |
ttributeReplaced | 监听属性替换 -当一个数据范围已经存在一个属性,向数据范围添加相同名称属性时自动触发替换方法 |
package com.lfg.listener;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class AttributeListener implements ServletContextAttributeListener {
@Override
public void attributeAdded(ServletContextAttributeEvent scae) {
System.out.println("ServletContext add attribute");
}
@Override
public void attributeRemoved(ServletContextAttributeEvent scae) {
System.out.println("ServletContext removed attribute");
}
@Override
public void attributeReplaced(ServletContextAttributeEvent scae) {
System.out.println("ServletContext replaced attribute");
}
}
WebListener
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
application.setAttribute("color","red");
application.setAttribute("color","green");
application.removeAttribute("color");
%>
</body>WebListener
</html>
package com.lfg.entity;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
public class Student implements HttpSessionBindingListener {
private int id;
private String name;
public Student() {
}
public Student(int id, String name) {
this.id = id;
this.name = name;
}
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;
}
@Override
public void valueBound(HttpSessionBindingEvent event) {
System.out.println("学生对象被绑定到session中了");
}
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
System.out.println("学生对象被从session中移除了");
}
}
<%@ page import="com.lfg.entity.Student" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
Student student = new Student(1,"mary");
session.setAttribute("stu",student);
session.removeAttribute("stu");
%>
</body>
</html>
package com.lfg.entity;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;
import java.io.Serializable;
public class Teacher implements HttpSessionActivationListener, Serializable {
private int id;
private String name;
public Teacher() {
}
public Teacher(int id, String name) {
this.id = id;
this.name = name;
}
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;
}
@Override
public void sessionWillPassivate(HttpSessionEvent se) {
System.out.println("数据钝化到磁盘中了");
}
@Override
public void sessionDidActivate(HttpSessionEvent se) {
System.out.println("数据活化到内存中了");
}
}
directory="d:\test"表示自定义钝化文件的存储路径,maxIdleSwap="1"表示超过1分钟未操作服务器会自动钝化。
<Manager className="org.apache.catalina.session.PersistentManager" saveOnRestart="true" maxIdleSwap="1">
<Store className="org.apache.catalina.session.FileStore" directory="d:\test"/>
</Manager>
<%@ page import="com.etime.lfg.Student" %>
<%@ page import="com.etime.lfg.Teacher" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
Teacher teacher = new Teacher(1,"mary");
session.setAttribute("teacher",teacher);
%>
</body>
</html>
<%@ page import="com.etime.lfg.Teacher" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
Teacher teacher = (Teacher)session.getAttribute("teacher");
out.print(teacher.getName());
%>
</body>
</html>
通过ServletContextListener监听,当Web应用上下文启动时,在ServletContext中添加一个List集合,用来准备存放在线的用户名;然后,可以通过HttpSessionAttributeListener监听器,当用户登录成功,把用户名设置到Session中时,同时将用户名存放到ServletContext中的List列表中;最后通过HttpSessionListener监听,当用户注销会话时,将用户名从应用上下文范围中的List列表中删除。
(1)创建登录页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="loginServlet" method="post"> 账号:<input type="text" name="username"><br> 密码:<input type="password" name="password"><br> <input type="submit" value="登录"> </form> </body> </html>
(2)创建用户登录的Servlet
package com.lfg.servlet; 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 java.io.IOException; @WebServlet("/loginServlet") public class LoginServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); String password = req.getParameter("password"); //默认登录成功 boolean res = true; if (res) { HttpSession session = req.getSession(); session.setAttribute("username",username); resp.sendRedirect("index.jsp"); } else { resp.sendRedirect("login.jsp"); } } }
(3)创建用户退出登录的Servlet
package com.lfg.servlet; 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 java.io.IOException; @WebServlet("/logoutServlet") public class LogoutServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); session.invalidate(); resp.sendRedirect("login.jsp"); } }
(4)创建监听器
package com.lfg.listener; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import javax.servlet.http.*; import java.util.ArrayList; import java.util.List; @WebListener public class UserListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener { ServletContext servletContext = null; @Override public void contextInitialized(ServletContextEvent sce) { //监听ServletContext对象的创建 //创建集合放入ServletContext对象中 List<String> list = new ArrayList<>(); servletContext = sce.getServletContext(); servletContext.setAttribute("users",list); } @Override public void attributeAdded(HttpSessionBindingEvent se) { //监听session中放入数据 //getName获取当前放入session中数据的key String name = se.getName(); if ("username".equals(name)) { //getValue获取当前放入session中数据的value String value = (String)se.getValue(); List<String> list = (List<String>)servletContext.getAttribute("users"); list.add(value); servletContext.setAttribute("users",list); } } @Override public void sessionDestroyed(HttpSessionEvent se) { //监听session的销毁 //退出登录时,将登录信息从ServletContext中的list里面移除掉 HttpSession session = se.getSession(); String username = (String)session.getAttribute("username"); List<String> list = (List<String>)servletContext.getAttribute("users"); list.remove(username); servletContext.setAttribute("users",list); } }
(5)创建显示在线用户页面index.jsp
<%@ page import="java.util.List" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> 欢迎您${sessionScope.username}<a href="logoutServlet">退出登录</a><br> 当前登录的用户有: <% List<String> users = (List<String>)application.getAttribute("users"); for (String user:users) { out.print(user+"<br>"); } %> </body> </html>