JavaWeb_Filter、Listener过滤器、监听器的基本应用

Filter 过滤器

  • Filter:过滤器,用来过滤网站的数据

    • 处理中文乱码
    • 登陆验证
  • 开发步骤

    • 导包
    • 编写过滤器
    • 实现Filter接口,重写对应的方法即可
    package zy.filter;
    
    import javax.servlet.*;
    import java.io.IOException;
    
    public class CharacterEncodingFilter implements Filter {
    
        //初始化:web服务器启动,就已经初始化了,随时等待对象出现
        public void init(FilterConfig filterConfig) throws ServletException {
            System.out.println("CharacterEncodingFilter初始化");
        }
    
        //Chain:链
        /*
        过滤器中所有代码,在过滤特定请求的时候都会执行
        必须要让过滤器继续同行
        chain.doFilter(request,response);
         */
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
    
            System.out.println("CharacterEncodingFilter执行前...");
            chain.doFilter(request,response);//让我们的请求继续走,如果不写,程序到这就停止了
            System.out.println("CharacterEncodingFilter执行后...");
    
        }
    
        //销毁:web服务器关闭的时候,过滤器会销毁
        public void destroy() {
            System.out.println("CharacterEncodingFilter销毁");
        }
    
    
    }
    
    
    • 配置web.xml
    <filter>
            <filter-name>CharacterEncodingFilter</filter-name>
            <filter-class>zy.filter.CharacterEncodingFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>CharacterEncodingFilter</filter-name>
            <!--只要是/servlet 的任何请求,都会经过这个过滤器-->
            <url-pattern>/servlet/*</url-pattern>
        </filter-mapping>
    

监听器

  • 实现一个监听器的接口:(有N种)

    • 编写一个监听器步骤

      • 实现监听器的接口
      package zy.listener;
      
      import javax.servlet.ServletContext;
      import javax.servlet.http.HttpSessionEvent;
      import javax.servlet.http.HttpSessionListener;
      
      //统计网站在线人数,统计Session
      public class OnlineCountListener implements HttpSessionListener {
      
          //创建session监听
          //一旦创建Session就会触发一次这个事件
          public void sessionCreated(HttpSessionEvent se) {
              ServletContext ctx = se.getSession().getServletContext();
              Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
      
              System.out.println(se.getSession().getId());
      
              if (onlineCount == null){
                  onlineCount = new Integer(1);
              }else {
                  int count = onlineCount.intValue();
                  onlineCount = new Integer(count + 1);
              }
      
              ctx.setAttribute("OnlineCount",onlineCount);
          }
          //销毁session监听
          //一旦创建Session就会触发一次这个事件
          public void sessionDestroyed(HttpSessionEvent se) {
      
          }
      }
      
      
      • 配置web.xml,注册监听器
      <!--注册监听器-->
      <listener>
          <listener-class>zy.listener.OnlineCountListener</listener-class>
      </listener>
      
      • 看情况是否使用

过滤器、监听器的常见应用

  • 监听器:GUI编程中经常使用
package zy.listener;

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

public class TestPanel {
    public static void main(String[] args) {
        Frame frame = new Frame("中秋节快乐");//新建一个窗体
        Panel panel = new Panel(null);//画板
        frame.setLayout(null);//设置窗体的布局

        frame.setBounds(300,300,500,500);
        frame.setBackground(Color.WHITE);//设置背景颜色

        panel.setBounds(50,50,300,300);
        panel.setBackground(new Color(0,0,0));

        frame.add(panel);

        frame.setVisible(true);

        //监听事件,监听关闭事件

        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        /*frame.addWindowListener(new WindowListener() {
            @Override
            public void windowOpened(WindowEvent e) {
                System.out.println("打开");
            }

            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("关闭ing");
                System.exit(0);//status为0 正常退出程序,status不为0  非正常退出程序
            }

            @Override
            public void windowClosed(WindowEvent e) {
                System.out.println("关闭ed");
            }

            @Override
            public void windowIconified(WindowEvent e) {

            }

            @Override
            public void windowDeiconified(WindowEvent e) {
                System.out.println("未激活");
            }

            @Override
            public void windowActivated(WindowEvent e) {
                System.out.println("激活");
            }

            @Override
            public void windowDeactivated(WindowEvent e) {

            }
        });*/


    }
}

  • 用户登录之后才能进入主页,用户注销之后就不能进入主页了

    • 用户登录之后,向Session中放入用户的数据
    • 进入主页的时候要判断用户是否已经登录;要求在过滤器中实现
    package zy.filter;
    
    import zy.util.Constant;
    
    import javax.servlet.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    public class SysFilter implements Filter {
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
            //ServletRequest    HttpServletRequest
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) resp;
    
            if (request.getSession().getAttribute(Constant.USER_SESSION) == null){
                response.sendRedirect("/error.jsp");
            }
    
            chain.doFilter(request,response);
    
        }
    
        @Override
        public void destroy() {
    
        }
    }
    
    

笔记

JavaWeb_Filter、Listener.md百度网盘链接
提取码: 8haa

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值