Filter(过滤器)与Listener(监听器)详解

11、Filter(重点)

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

  • 处理中文乱码
  • 登陆验证...

Filter(过滤器)与Listener(监听器)详解_第1张图片

Filter开发步骤:

  1. 导包

  2. 编写过滤器

    1. 导包不要错

      Filter(过滤器)与Listener(监听器)详解_第2张图片

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

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

      
          ShowServlet
          com.kuang.servlet.ShowServlet
      
      
          ShowServlet
          /servlet/show
      
      
          ShowServlet
          /show
      
      
      
          CharacterEncodingFilter
          com.kuang.filter.CharacterEncodingFilter
      
      
          CharacterEncodingFilter
          
          /servlet/*
          
      
      

12、监听器

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

  1. 编写一个监听器

    实现监听器的接口...

    //统计网站在线人数 : 统计session
    public class OnlineCountListener implements HttpSessionListener {
    
        //创建session监听:看你的一举一动
        //一旦创建一个session就会触发一次这个事件!
        public void sessionCreated(HttpSessionEvent httpSessionEvent) {
            ServletContext context = httpSessionEvent.getSession().getServletContext();
    
            System.out.println(httpSessionEvent.getSession().getId());
    
            Integer onlineCount = (Integer) context.getAttribute("OnlineCount");
    
            if (onlineCount==null){
                onlineCount = new Integer(1);
            }else {
                int count = onlineCount.intValue();
                onlineCount = new Integer(count+1);
            }
    
            context.setAttribute("OnlineCount",onlineCount);
        }
    
        //销毁session监听
        //一旦销毁session就会触发一次这个事件!
        public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
            ServletContext context = httpSessionEvent.getSession().getServletContext();
            Integer onlineCount = (Integer) context.getAttribute("OnlineCount");
    
            if (onlineCount==null){
                onlineCount = new Integer(0);
            }else {
                int count = onlineCount.intValue();
                onlineCount = new Integer(count-1);
            }
    
            context.setAttribute("OnlineCount",onlineCount);
        }
    
        /*
        Session销毁:
        1. 手动销毁 getSession.invalidate()
        2. 自动销毁 在web.xml中设置session过期时间
         */
    }
    
  2. web.xml中注册监听器

    
    
        com.kuang.listener.OnlineCountListener
    
    
  3. 看情况是否使用!

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

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

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

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

        panel.setBounds(70,70,70,70); //设置背景颜色
        panel.setBackground(Color.GREEN);

        frame.add(panel);
        frame.setVisible(true);

        //监听事件,监听关闭事件,使用适配器
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

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

Filter(过滤器)与Listener(监听器)详解_第3张图片

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

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

    //ServletRequest    HttpServletRequest
    HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
    
    if (httpServletRequest.getSession().getAttribute(Constant.USER_SESSION)==null){
        httpServletResponse.sendRedirect("/error.jsp");
    }
    
    filterChain.doFilter(servletRequest, servletResponse);
    

项目全部代码:

public class Constant {
    public final static String USER_SESSION = "USER_SESSION";
}
=============================================================
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端请求的参数
        String username = req.getParameter("username");

        if (username.equals("admin")){ //登陆成功
            req.getSession().setAttribute(Constant.USER_SESSION,req.getSession().getId());
            resp.sendRedirect("/sys/success.jsp");
        }else { //登录失败
            resp.sendRedirect("/error.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
==========================================================================
public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Object user_session = req.getSession().getAttribute(Constant.USER_SESSION);
        
        if (user_session!=null){
            req.getSession().removeAttribute(Constant.USER_SESSION);
            resp.sendRedirect("/Login.jsp");
        }else {
            resp.sendRedirect("/Login.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
===============================================================================
public class SysFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        /*
        实现会员分级:
            if (req.getSession().setAttribute(Constant.USER_SESSION).level==VIP1){
                response.sendRedirect("/vip1/index.jsp");
            }
            if (req.getSession().setAttribute(Constant.USER_SESSION).level==VIP2){
                response.sendRedirect("/vip2/index.jsp");
            }
            if (req.getSession().setAttribute(Constant.USER_SESSION).level==VIP3){
                response.sendRedirect("/vip3/index.jsp");
            }
         */

        //ServletRequest    HttpServletRequest
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        if (httpServletRequest.getSession().getAttribute(Constant.USER_SESSION)==null){
            httpServletResponse.sendRedirect("/error.jsp");
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    public void destroy() {
    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title



错误

没有权限,用户名错误

返回登录页面

==================================================================== <%@ page contentType="text/html;charset=UTF-8" language="java" %> Title

主页

注销

======================================================================= <%@ page contentType="text/html;charset=UTF-8" language="java" %> Title

登录

用户名:
======================================================================== LoginServlet com.kuang.servlet.LoginServlet LoginServlet /servlet/login LogoutServlet com.kuang.servlet.LogoutServlet LogoutServlet /servlet/logout SysFilter com.kuang.servlet.SysFilter SysFilter /sys/*

你可能感兴趣的:(Filter(过滤器)与Listener(监听器)详解)