Cookie,Session,三大域对象,过滤器,监听器

发布 | 2024-08-25 | JavaWeb

Cookie 与 Session

Cookie

Cookie 是服务器发送到客户端并存储在客户端的一小段数据,用于识别用户或保存用户偏好设置等信息。

设置 Cookie

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/servletCookie")
public class servletCookie extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 创建一个 Cookie
        Cookie cookie = new Cookie("ZHANGSAN", "001");

        // 设置 Cookie 的路径
        cookie.setPath("/");

        // 添加 Cookie 到响应中
        resp.addCookie(cookie);
    }
}

Session

Session 用于在服务器端存储每个用户的会话数据,通常使用 HttpSession 来管理。

使用 Session

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/servletSession")
public class servletSession extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取或创建 Session
        HttpSession session = req.getSession();
        
        // 设置属性
        session.setAttribute("user", "Alice");
        
        // 获取属性
        String user = (String) session.getAttribute("user");
        
        // 设置响应内容类型为 HTML
        resp.setContentType("text/html;charset=utf-8");
        
        // 向客户端返回响应内容
        resp.getWriter().write("<html><body>");
        resp.getWriter().write("<h1>User: " + user + "</h1>");
        resp.getWriter().write("</body></html>");
    }
}

三大域对象

在 Servlet 中,三大域对象用于在不同组件之间共享数据:

  • ServletContext:表示整个 Web 应用程序的上下文,适用于在不同的 Servlet 和 JSP 页面之间共享数据。
  • HttpSession:表示用户的会话,适用于在用户会话期间共享数据。
  • HttpServletRequest:表示单个 HTTP 请求,适用于在同一个请求范围内共享数据。

设置三大域对象

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/setScope")
public class setScope extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求域对象
        req.setAttribute("user", "zhangSan");

        // 设置应用域对象
        this.getServletContext().setAttribute("user", "wangWu");

        // 设置 session 域对象
        req.getSession().setAttribute("user", "sushi");

        // 设置响应内容类型
        resp.setContentType("text/html;charset=utf-8");

        // 向客户端返回响应内容
        resp.getWriter().write("设置三大域对象成功<br>");
        resp.getWriter().write("请求域对象:" + req.getAttribute("user") +
                "<br>session域对象:" + req.getSession().getAttribute("user") +
                "<br>应用域对象:" + req.getServletContext().getAttribute("user"));
    }
}

获取三大域对象

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/getScope")
public class getScope extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应内容类型
        resp.setContentType("text/html;charset=utf-8");

        // 获取并展示三大域对象的值
        resp.getWriter().write("获取三大域对象成功<br>");
        resp.getWriter().write("请求域对象:" + req.getAttribute("user") +
                "<br>session域对象:" + req.getSession().getAttribute("user") +
                "<br>应用域对象:" + req.getServletContext().getAttribute("user"));
    }
}

过滤器 (Filter)

过滤器用于在请求到达 Servlet 或 JSP 页面之前,对请求进行预处理,或者在响应发送到客户端之前对响应进行后处理。

创建 Filter

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import java.io.IOException;

public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化 Filter
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 前处理逻辑
        System.out.println("Request is being processed");
        
        // 继续执行请求
        chain.doFilter(request, response);
        
        // 后处理逻辑
        System.out.println("Response is being processed");
    }

    @Override
    public void destroy() {
        // 清理资源
    }
}

使用注解配置 Filter

可以使用 @WebFilter 注解来配置过滤器,无需在 web.xml 文件中进行配置。

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import java.io.IOException;

@WebFilter("/*") // 过滤所有请求
public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化 Filter
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 前处理逻辑
        System.out.println("Request is being processed");
        
        // 继续执行请求
        chain.doFilter(request, response);
        
        // 后处理逻辑
        System.out.println("Response is being processed");
    }

    @Override
    public void destroy() {
        // 清理资源
    }
}

web.xml 中配置 Filter

如果不使用注解,可以在 web.xml 文件中配置过滤器:

<filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>com.example.MyFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

监听器 (Listener)

监听器用于监听 Web 应用程序的生命周期事件,如创建和销毁 SessionServletContext 等,还可以监听属性的变化。

ServletContextListener

ServletContextListener 用于监听 ServletContext 的创建和销毁。

import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;

@WebListener
public class MyServletContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // ServletContext 初始化时触发
        System.out.println("ServletContext 初始化");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // ServletContext 销毁时触发
        System.out.println("ServletContext 销毁");
    }
}

ServletContextAttributeListener

ServletContextAttributeListener 用于监听 ServletContext 属性的添加、移除和替换。

import jakarta.servlet.ServletContextAttributeEvent;
import jakarta.servlet.ServletContextAttributeListener;
import jakarta.servlet.annotation.WebListener;

@WebListener
public class MyServletContextAttributeListener implements ServletContextAttributeListener {
    @Override
    public void attributeAdded(ServletContextAttributeEvent event) {
        // 属性添加时触发
        System.out.println("属性添加: " + event.getName() + " = " + event.getValue());
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent event) {
        // 属性移除时触发
        System.out.println("属性移除: " + event.getName());
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent event) {
        // 属性替换时触发
        System.out.println("属性替换: " + event.getName() + " = " + event.getValue());
    }
}

HttpSessionListener

HttpSessionListener 用于监听 HttpSession 的创建和销毁。

import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;
import jakarta.servlet.annotation.WebListener;

@WebListener
public class MyHttpSessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        // Session 创建时触发
        System.out.println("Session 创建");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        // Session 销毁时触发
        System.out.println("Session 销毁");
    }
}

HttpSessionAttributeListener

HttpSessionAttributeListener 用于监听 HttpSession 属性的添加、移除和替换。

import jakarta.servlet.http.HttpSessionAttributeListener;
import jakarta.servlet.http.HttpSessionBindingEvent;
import jakarta.servlet.annotation.WebListener;

@WebListener
public class MyHttpSessionAttributeListener implements HttpSessionAttributeListener {
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        // Session 属性添加时触发
        System.out.println("Session 属性添加: " + event.getName() + " = " + event.getValue());
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        // Session 属性移除时触发
        System.out.println("Session 属性移除: " + event.getName());
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        // Session 属性替换时触发
        System.out.println("Session 属性替换: " + event.getName() + " = " + event.getValue());
    }
}

ServletRequestListener

ServletRequestListener 用于监听请求的创建和销毁。

import jakarta.servlet.ServletRequestEvent;
import jakarta.servlet.ServletRequestListener;
import jakarta.servlet.annotation.WebListener;

@WebListener
public class MyServletRequestListener implements ServletRequestListener {
    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        // 请求创建时触发
        System.out.println("请求创建");
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        // 请求销毁时触发
        System.out.println("请求销毁");
    }
}

ServletRequestAttributeListener

ServletRequestAttributeListener 用于监听请求属性的添加、移除和替换。

import jakarta.servlet.ServletRequestAttributeListener;
import jakarta.servlet.ServletRequestAttributeEvent;
import jakarta.servlet.annotation.WebListener;

@WebListener
public class MyServletRequestAttributeListener implements ServletRequestAttributeListener {
    @Override
    public void attributeAdded(ServletRequestAttributeEvent event) {
        // 请求属性添加时触发
        System.out.println("请求属性添加: " + event.getName() + " = " + event.getValue());
    }

    @Override
    public void attributeRemoved(ServletRequestAttributeEvent event) {
        // 请求属性移除时触发
        System.out.println("请求属性移除: " + event.getName());
    }

    @Override
    public void attributeReplaced(ServletRequestAttributeEvent event) {
        // 请求属性替换时触发
        System.out.println("请求属性替换: " + event.getName() + " = " + event.getValue());
    }
}

© 著作权归作者所有

本文由 趣代码Blog 创作,采用 知识共享署名4.0 国际许可协议进行许可,本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。

评论关闭