Filter and Listener of JavaWeb

Filter and Listener of JavaWeb

Filter: filter

Implementation process:

Instructions:

Detailed filter configuration

Listener: listener

Event monitoring mechanism

ServletContextListener

Instructions:

Case of login interception using Filter


Filter: filter

      Filter: When accessing the resources of the server, the filter can intercept the request and perform some special functions. Generally used to complete common operations. Such as: login verification, unified encoding processing, sensitive character filtering...

      The filter is equivalent to a filter between the browser and the Web resource. A series of filters are used to modify, judge, and intercept the request before accessing the resource, and the response can also be modified, judged, and intercepted.

Implementation process:

  1. The client sends a request, first passes through the filter, if the filter is allowed, then it can go to the servlet

  2. If there are multiple filters, they will be queued according to the registered mapping order. As long as there is a filter that is not allowed, then the subsequent filters and our servlet will not receive the request.

How to use :

        1. Define a class that implements the interface Filter.

        2. Rewrite the method (execute the interception action)

        3. Configure the interception path: use the annotation @WebFilter or web.xml

@WebFilter("/*")//访问所有资源之前,都会执行该过滤器
public class FilterDemo1 implements Filter {
       @Override
       public void init(FilterConfig filterConfig) throws ServletException {
            //过滤器初始化的方法,一般用于申请资源
            // init:在服务器启动后,会创建Filter对象,然后调用init方法。只执行一次。用于加载资源
       }
            
       @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
           //执行拦截的动作,具体的拦截逻辑写在这里  
           //doFilter:每一次请求被拦截资源时,会执行。执行多次         
           System.out.println("filterDemo1被执行了....");
            
           //放行
           filterChain.doFilter(servletRequest,servletResponse);
            
       }
            
       @Override
       public void destroy() {
            //过滤器销毁的方法,一般用于释放资源
            //destroy:在服务器关闭后,Filter对象被销毁。如果服务器是正常关闭,则会执行destroy方法。只执行一次。用于释放资源
       }
}

Detailed filter configuration

       Interception path configuration:

                1.  Specific resource path: /index.jsp The filter will only be executed when the index.jsp resource is accessed

                2.  Intercept directory: /user/* When accessing all resources under /user, the filter will be executed

                3.  Suffix name interception: *.jsp When accessing all resources with the suffix name jsp, the filter will be executed

                4.  Intercept all resources: /* When all resources are accessed, the filter will be executed

Listener: listener

A special component defined in the Servlet specification is used to listen to events generated by the Servlet container and process them accordingly.

Event monitoring mechanism

            * Event: one thing

            * Event source: the place where the event occurred

            * Listener: an object

            * Registered listener: bind the event, event source, and listener together. When an event occurs on the event source, execute the listener code

ServletContextListener

           The ServletContextListener will be notified when the ServletContext is created and closed.

           The listener needs to be configured in web.xml.

How to use :

           1. Define a class that implements the ServletContextListener interface.

           2. Rewrite method.

           3. Make the configuration

 

ServletContextListener:监听ServletContext对象的创建和销毁
* 方法:
      * void contextDestroyed(ServletContextEvent sce) :ServletContext对象被销毁之前会调用该方法
      * void contextInitialized(ServletContextEvent sce) :ServletContext对象创建后会调用该方法

Case of login interception using Filter

@WebFilter("*.jsp")
public class FilterTest1 implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //判断是否已经登录了,如果没有登录就需要跳转到登录界面,但是如果访问的资源路径本来
        //就是登录页面,那么就不需要拦截了,这里需要进行判断排除

        //记得强制转型
        HttpServletRequest request = (HttpServletRequest)req ;

        //获取session对象,看看对应的属性是否有值
        HttpSession session = request.getSession();
        Object  login = session.getAttribute("login");

        //获取url路径,看看里面是否是登录资源相关的
        String requestURI = request.getRequestURI();

        //在过滤掉登录相关时,一定要排除一些js,css文件
        if (login != null || requestURI.contains("/longin.jsp") || requestURI.contains("/css/") ||
                requestURI.contains("/js/") || requestURI.contains("/fonts/") ) {
            chain.doFilter(req, resp);
        } else {
            request.getRequestDispatcher("/longin.jsp").forward(request, resp);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}

It is not easy to create. If this blog is helpful to you, please remember to leave a message + like it. 

Guess you like

Origin blog.csdn.net/promsing/article/details/114438925