首页 > 技术文章 > 过滤器 监听器

wellzzz 2021-07-21 20:14 原文

Filter(重点)

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

  • 处理中文乱码
  • 登录验证

Filter开发步骤

  1. 导包

            <!--连接数据库-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.45</version>
            </dependency>
    
  2. 编写过滤器

    1. 导包不要错

  实现Filter接口,重写对应的方法即可

  ```java
  public class CharacterEncodingFilter implements Filter {
      //初始化:web服务器启动,就初始化了,随时等待过滤对象出现
      public void init(FilterConfig filterConfig) throws ServletException {
          System.out.println("CharacterEncodingFilter初始化");
      }
  
      //chain:链
      /*
      1.过滤中的所有代码,在过滤特点请求的时候都会执行
      2.必须要让过滤器继续同行
          chain.doFilter(request,response);
      */
      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
          request.setCharacterEncoding("GBK");
          response.setCharacterEncoding("GBK");
          response.setContentType("text/html;charset=UTF-8");
          System.out.println("执行前......");
          chain.doFilter(request,response);//让我们的请求继续走,如果不写,程序到这里就被拦截停止;
          System.out.println("执行后......");
  
      }
      //销毁:web服务器关闭的时候,过滤器会被销毁
      public void destroy() {
          System.out.println("CharacterEncodingFilter销毁");
      }
  }
  ```
  1. 在web.xml中配置Filter

        <filter>
            <filter-name>CharacterEncodingFilter</filter-name>
            <filter-class>com.su.filter.CharacterEncodingFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>CharacterEncodingFilter</filter-name>
            <!--只要是/servlet的任何请求,会经过这个过滤器-->
            <url-pattern>/servlet/*</url-pattern>
            <!--<url-pattern>/*</url-pattern>-->
        </filter-mapping>
    

监听器

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

  1. 编写一个监听器

    实现监听器的接口

    //统计网站在线人数:统计session
    public class OnlineCountListener implements HttpSessionListener {
    
        //创建session的监听:看你的一举一动
        //一旦创建Session就会触发一次这个事件!
        public void sessionCreated(HttpSessionEvent httpSessionEvent) {
            ServletContext ctx = httpSessionEvent.getSession().getServletContext();
            Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
    
            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 httpSessionEvent) {
            ServletContext ctx = httpSessionEvent.getSession().getServletContext();
    
            Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
    
            if (onlineCount == null) {
                onlineCount = new Integer(0);
            }else {
                int count = onlineCount.intValue();
                onlineCount = new Integer(count-1);
            }
            ctx.setAttribute("OnlineCount",onlineCount);
    
        }
    
    /*
    Session销毁:
    1.手动销毁  httpSessionEvent.getSession().invalidate();
    2.自动销毁
    */
    
  2. web.xml注册监听器

        <listener>
            <listener-class>com.su.listener.OnlineCountListener</listener-class>
        </listener>
    
            <!-- 一分钟销毁-->
        <session-config>
            <session-timeout>1</session-timeout>
        </session-config>
    
  3. 看情况是否使用

过滤器、监听器常见应用

监听器:GUI编程中经常使用

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(new Color(0, 0, 255));//设置背景颜色

        panel.setBounds(50, 50, 300, 300);

        panel.setBackground(new Color(0, 255, 0));//设置背景颜色

        frame.add(panel);

        frame.setVisible(true);
        //监听事件,监听关闭事件
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
            }
        });
    }
}

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

  1. 用户登录之后,向Session中放入用户的数据

  2. 进入主页的时候要判断用户是否已经登录; 要求:在过滤器中实现

            //ServletRequest   强转   HttpServletRequest
    
            HttpServletRequest rep1 = (HttpServletRequest) rep;
            HttpServletResponse resp1 = (HttpServletResponse) resp;
    
            if(rep1.getSession().getAttribute("USER_SESSION")==null){
                resp1.sendRedirect("/r/error.jsp");
            }
            filterChain.doFilter(rep,resp);
    
    

    游戏中VIP过滤

            /*   游戏里的vip过滤
                if(req.getSession().setAttribute("USER_SESSION".level==VIP1){
                    resp.sendRedirect("/r/vip1/index.jsp")
                }
                if(req.getSession().setAttribute("USER_SESSION".level==VIP2){
                    resp.sendRedirect("/r/vip2/index.jsp")
                }
                if(req.getSession().setAttribute("USER_SESSION".level==VIP3){
                    resp.sendRedirect("/r/vip3/index.jsp")
                }
            */
    

推荐阅读