16、Filter、Listener

文章目录

Filter

Filter:过滤器,用来过滤网站的请求。

  • 处理中文乱码(截止目前我们都是在每个Servlet上处理POST请求的中文乱码,和Response响应的中文乱码)
  • 坏的请求等

创建一个Maven的Web项目。

pom.xml

<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.3</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
    </dependency>
</dependencies>

web.xml

<?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">
</web-app>

创建Servlet

package org.westos.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 java.io.IOException;

/**
 * urlPatterns映射路径可以设置多个,一个Servlet可以对应多个请求路径,但是一个请求路径只能对应一个Servlet
 * @author lwj
 * @date 2020/8/27 18:21
 */
@WebServlet(name = "MyServlet", value = {"/show", "/servlet/show"})
public class MyServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().write("世界那么大!");
        /*在CharacterEncodingFilter过滤器中处理中文乱码问题,而不是在每个Servlet中处理*/
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

创建Filter

在这里插入图片描述

修改创建Filter注解版的模板代码

在这里插入图片描述

package org.westos.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * 拦截/servlet/*下的所有请求
 * @author lwj
 * @date 2020/8/27 18:15
 */
@WebFilter(filterName = "CharacterEncodingFilter", value = {"/servlet/*"})
public class CharacterEncodingFilter implements Filter {
    @Override
    public void destroy() {
        System.out.println("CharacterEncodingFilter销毁");
    }

    /**
     * 1、过滤器中的所有代码,在过滤特定请求时都会执行
     * 2、必须要让过滤器继续通行,chain.doFilter(req, resp)
     * @param req
     * @param resp
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //处理POST请求的中文乱码问题
        resp.setContentType("text/html;charset=utf-8");
        //处理响应的中文乱码问题

        System.out.println("CharacterEncodingFilter执行前...");
        System.out.println(chain);
        chain.doFilter(req, resp);
        //让我们的请求继续走,如果不写这条代码,那么程序到这里就被拦截了
        System.out.println("CharacterEncodingFilter执行后...");
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        System.out.println("CharacterEncodingFilter初始化");
    }

}

重点:

Web服务器启动,Filter初始化,随时拦截Servlet。

Web服务器关闭时,Filter销毁。

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

Listener

package org.westos.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * 统计在线人数:统计Session
 * 监听器有很多很多种,我们目前只学习HttpSessionListener,重写接口中的默认方法
 * @author lwj
 * @date 2020/8/27 19:14
 */
@WebListener
public class OnlineCountListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        //一旦创建Session就会触发这个事件
        ServletContext servletContext = se.getSession().getServletContext();
        //获取最高的域对象
        Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount");
        if (onlineCount == null) {
            servletContext.setAttribute("OnlineCount", 1);
        } else {
            servletContext.setAttribute("OnlineCount", onlineCount + 1);
        }
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext servletContext = se.getSession().getServletContext();
        Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount");
        if (onlineCount == null) {
            servletContext.setAttribute("OnlineCount", 0);
        } else {
            servletContext.setAttribute("OnlineCount", onlineCount - 1);
        }
    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页</title>
</head>
<body>
    <h1>当前网站有<span>${applicationScope.OnlineCount}</span>人在线。</h1>
</body>
</html>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值