JavaWeb--过滤器与监听器

前言

  • Java Web 其实就是一个技术的总和,把Web看成一个容器而已主要使用JavaEE技术来实现.在加上各种中间件。
  • 整个javaWeb阶段的内容通过实际的案例贯穿学习, 所涉及到的技术知识点会在案例中根据不同的需求引入。
  • 首先了解javaWeb的整个技术体系,掌握常用的技术知识点。

我会将JavaWeb分为8篇左右的文章来记录自己的学习过程,也方便大家逐级递增难度的学习,如有错误或遗漏欢迎大家指出。

注:本篇文章承接上一篇JavaWeb文章JavaWeb--JavaBean与三层架构
下面我们进入正题!

11、Filter(重点)

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

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

Filter开发步骤:

  1. 导包
  2. 编写过滤器
    1. 导包不要错 import javax.servlet.*;
    2. 实现Filter接口,重写对应的方法
    3. 在web.xml中配置Filter

CharacterEncodingFilter:

public class CharacterEncodingFilter implements Filter {

    //初始化    web服务器启动就初始化了
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CharacterEncodingFilter初始化");

    }
    //Chain:链
    /*
    * 1.过滤中的所有代码,在过滤特定请求的时候都会执行
    * 2.必须要让过滤器继续通行filterChain.doFilter(servletRequest,servletResponse);
    * */
    @Override
    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服务器关闭的时候销毁
    @Override
    public void destroy() {
        System.out.println("CharacterEncodingFilter销毁");
    }
}

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">
    
    <servlet>
        <servlet-name>ShowServlet</servlet-name>
        <servlet-class>com.qjd.servlet.ShowServlet</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>ShowServlet</servlet-name>
        <url-pattern>/servlet/show</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ShowServlet</servlet-name>
        <url-pattern>/show</url-pattern>
    </servlet-mapping>

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

ShowServlet:

public class ShowServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        resp.setCharacterEncoding("utf-8");
//        req.setCharacterEncoding("utf-8");
        resp.getWriter().write("你好啊");
    }

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

12、监听器

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

  1. 编写一个监听器(实现监听器的接口)

    //统计网站在线人数:统计session
    public class OnlineCountListener implements HttpSessionListener{
        //    创建session监听
        //    一旦创建Session就会触发一次这个事件
        @Override
        public void sessionCreated(HttpSessionEvent se) {
    
            System.out.println(se.getSession().getId());
            ServletContext ctx = se.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就会触发一次这个事件
        @Override
        public void sessionDestroyed(HttpSessionEvent se) {
    
            ServletContext ctx = se.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.手动销毁  se.getSession().invalidate();
        * 2.自动销毁  (在web.xml中配置)
        *   <session-config>
            <session-timeout>1</session-timeout>
            </session-config>
        * */
    
    }
    
  2. 配置监听器(web.xml中注册)

    <!--  注册监听器  -->
        <listener>
            <listener-class>com.qjd.listener.OnlineCountListener</listener-class>
        </listener>
    
  3. 根据情况是否使用

  4. 测试结果

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

  • 监听关闭事件(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, 255, 34));
    
            panel.setBounds(50,50,300,300);
    
            panel.setBackground(new Color(128, 0, 255));
    
            frame.add(panel);
    
            frame.setVisible(true);
    
            //监听关闭事件
            frame.addWindowListener(new WindowListener() {
                @Override
                public void windowOpened(WindowEvent e) {
                    System.out.println("打开");
                }
    
                @Override
                public void windowClosing(WindowEvent e) {
                    System.out.println("正在关闭");
                    System.exit(0);//0是正常终止。1是非正常终止
                }
    
                @Override
                public void windowClosed(WindowEvent e) {
                    System.out.println("已关闭");
                }
    
                @Override
                public void windowIconified(WindowEvent e) {
    
                }
    
                @Override
                public void windowDeiconified(WindowEvent e) {
    
                }
    
                @Override
                public void windowActivated(WindowEvent e) {
                    System.out.println("激活");
                }
    
                @Override
                public void windowDeactivated(WindowEvent e) {
                    System.out.println("未激活");
                }
            });
    
    
        }
    }
    
  • 用户登录才能进入主页,用户注销后就不能进入主页(必须通过登录才能访问登录成功主页,通过直接访问登录成功主页不能进入)

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

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

    public class SysFilter implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
            //ServletRequest      HttpServlet
            HttpServletRequest request1 = (HttpServletRequest) servletRequest;
            HttpServletResponse response1 = (HttpServletResponse) servletResponse;
            String user_session = (String) request1.getSession().getAttribute(Constant.USER_SESSION);
    
    
            if(user_session == null){
                response1.sendRedirect("/error.jsp");
    
            }
    
    
            filterChain.doFilter(servletRequest,servletResponse);
        }
    
        @Override
        public void destroy() {
    
        }
    }
    
    

整体步骤:

  1. 制定登录页面Login.jsp
  2. LoginServlet
  3. 登录成功进入success.jsp
  4. 登录失败进入error.jsp
  5. 权限验证SysFilter
  6. 解决session名字重用问题(定义常量Constant)
  7. 配置web.xml
posted @ 2022-08-29 18:57  鹤鸣呦呦、、  阅读(39)  评论(0编辑  收藏  举报