Filter,Listener

过滤器Filter

实现javax.servlet.Filter;

//只要是/servlet下的任何请求,都会经过此过滤器,
@WebFilter(filterName = "encodingFilter", value = {"/servlet/*"})
public class EncodingFilter implements Filter {
    @Override
    //初始化,服务器启动时初始化
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤前");
    }

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

    @Override
    //销毁,服务器关闭时销毁
    public void destroy() {
        System.out.println("销毁");
    }
}

监听器Listener

需要实现什么功能的监听器,就要实现相应的类

//统计在线人数,通过session,所以implements HttpSessionListener
@WebListener(value = "onlineCountListener")
public class OnlineCountListener implements HttpSessionListener {
    @Override
    //创建session监听,创建session时触发
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext context = se.getSession().getServletContext();
        Object c = context.getAttribute("count");
        System.out.println("666==" + c);
        int count;
        if (c == null) {
            count = 1;
        } else {
            count = (int) c + 1;
        }
        context.setAttribute("count", count);
    }

    @Override
    //销毁session时触发
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext context = se.getSession().getServletContext();
        int count = (int) context.getAttribute("count");
        count -= 1;
        context.setAttribute("count", count);

    }
}
<h1>
    <%--三个等价--%>
    <span><%= getServletConfig().getServletContext().getAttribute("count")%></span>online
    <span>${applicationScope.count}</span>online
    <span>${applicationScope.get("count")}</span>online
</h1>
posted @   jpy  阅读(18)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示