首页 > 编程语言 >JAVAWeb - Filter(过滤器)

JAVAWeb - Filter(过滤器)

时间:2022-11-04 17:46:01浏览次数:37  
标签:JAVAWeb void System public Filter println 监听器 过滤器 onlineCount

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

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

过滤器的分析:

我们用户在使用web浏览器访问web服务器的时候;以往的过程都是web服务器直接去寻址拿资源(servlet,jsp,HTML,静态资源),然而在请求处理的时候,我们通常会因为请求和响应的数据结构类型不同,导致网页出现乱码,或者崩溃的状态。

我们在web服务器和静态资源中加了一层过滤器,专门对请求和响应的码进行处理,统一规格化请求和响应的代码,就可以避免乱码的情况。

一:导包

  <dependencies>
        <!--Servlet  的依赖-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <!--jsp的依赖-->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>
        <!--jstl 表达式的依赖-->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- taglibs 标签库 -->
        <dependency>
            <groupId>org.apache.taglibs</groupId>
            <artifactId>taglibs-standard-impl</artifactId>
            <version>1.2.5</version>
            <scope>runtime</scope>
        </dependency>

    </dependencies>

一般在maven中导入这四个包就可以完成了,过滤器一般的实现只需要这四个包

二:编写过滤器

导包:java.servlet

实现Filter接口:

注意点:过滤中一定要包含这个方法   filterChain.doFilter  不然请求就会停在监听器中

public class CharacterEncodingFilteer implements Filter {
    //初始化:在web服务器启动的时候就已经初始化完成了
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CharacterEncodingFilter已经初始化");
    }
//chain
    /*
    1.过滤器中的代码,在过滤特定需求的请求中都会执行
    2.必须要让过滤器往下进行:filterChain.doFilter
     */
    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已经销毁");
    }
}

  在web.xml中配置Filter的作用域

  <filter>
    <filter-name>CharacterEncodingFilteer</filter-name>
    <filter-class>top.lostyou.jsp.Filter.CharacterEncodingFilteer</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilteer</filter-name>
    <!-- 过滤Filter包下的文件的请求-->
    <url-pattern>/Filter/*</url-pattern>
  </filter-mapping>

监听器:实现一个监听器的接口(很多)

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

//统计在线人数:统计session
public class OnlineCountLinster implements HttpSessionListener {
    //创建session的监听
    //一旦创建一个session就会触发一次这个事件
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext ctx = se.getSession().getServletContext();
        System.out.println(se.getSession().getId());
        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 se) {
        ServletContext ctx = se.getSession().getServletContext();
        System.out.println(se.getSession().getId());
        se.getSession().invalidate();
        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);
    }
}

 2.在web.xml中注册监听器,并设置session的过期事件

  <!--注册监听器-->
  <listener>
    <listener-class>top.lostyou.jsp.linster.OnlineCountLinster</listener-class>
  </listener>
  <session-config>
    <session-timeout>1</session-timeout>
  </session-config>

过滤器和监听器的常见应用:

监听器GUI的实现:

public class TestPanel  {
    public static void main(String[] args) {
        Frame frame = new Frame("监听器GUI测试");//新建一个窗体
        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 WindowListener() {
            public void windowOpened(WindowEvent e) {
                System.out.println("打开");
            }

            public void windowClosing(WindowEvent e) {
                System.out.println("关闭ing");
                System.exit(0);
            }

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

            public void windowIconified(WindowEvent e) {

            }

            public void windowDeiconified(WindowEvent e) {

            }

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

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

    }
}

 以上通过GUI的方法实现窗口:

在运行以后一个窗体被呈现了出来

此时我们对窗体的操作都使用监听器去监听;

每当我们执行一个事件都可能会有反馈,就是监听器的作用。

标签:JAVAWeb,void,System,public,Filter,println,监听器,过滤器,onlineCount
From: https://www.cnblogs.com/5ran2yl/p/16858582.html

相关文章

  • javaweb期中考试
    bean类packageBean;publicclassbean{privateStringzhuti;privateStringmudi;privateStringhuodongleixing;privateStringtime;privateStringdidian;privat......
  • .Netcore IOptions<LoggerFilterOptions> 获取的顺序
    .netcore配置文件的日志级别:{"Logging":{"LogLevel":{"Default":"Information","Microsoft":"Trace","Microsoft.Hosting.Lifetime......
  • 状态估计和KalmanFilter公式的推导与应用
    状态估计的概率解释运动和观测方程:\[\left\lbrace\begin{array}{l}x_k=f(x_{k_1},u_k)+w_k\\z_k=h(y_j,x_k)+v_{k,j}\end{array}\right.\qquad{k=1......
  • WallFilter_简介
    遇到的问题:Caused by: java.sql.SQLException: sql injection violation, dbType mysql, druid-version 1.2.8, part alway true condition not allow : ......
  • spring-boot-2.0.3源码篇 - filter的注册,值得一看
    开心一刻过年女婿来岳父家走亲戚当时小舅子主就问:姐夫,你什么时候能给我姐幸福,让我姐好好享受生活的美好。你们这辈子不准备买一套大点的房子吗?姐夫说:现在没钱啊......
  • springboot javax.servlet.Filter使用
    请求拦截器优点:1、拦截非法请求重定向2、验证用户token下面是demo程序,有问题的可以在评论区留言@WebFilter(filterName="authenticationFilter",urlPatterns={"/user/*......
  • JAVAWeb - JSP标签
    一:EL 表达式获取数据执行运算获取web开发的常用的对象二:JSP标签<jsp:forwardpage="/jsptag2.jsp"><jsp:paramname="name"value="maming"></jsp:param>......
  • SpringBoot笔记:拦截器Interceptor和过滤器Filter
    一、拦截器InterceptorSpringBoot中定义拦截器与MVC中是一样的,区别在于拦截器的配置,MVC是配置在配置文件中的,SpringBoot中则是配置在配置类中的。(SpringBoot中的配置类需......
  • JavaWeb三大组件之Servlet学习
    JavaWeb三大组件之Servlet学习平时直接用springmvc较多,都没怎么接触底层的Servlet,导致对一些基本的知识点了解都不够,所以今天专门的抽出时间来学习一下带着问题出发,看下可以......
  • JavaWeb三大组件之Filter学习详解
    JavaWeb三大组件之Filter学习详解Filter基本上可以说存在所有的JavaWeb项目中,比如最基本的一个请求参数的编码​​CharacterEncodingFilter​​,大家一般都会配置下,那么filte......