[Winter vacation 2020-JAVA] day12-Fiter&Listener

Posted by popcornplya on Thu, 23 Jan 2020 03:15:33 +0100

Write in front: Recently, I have been reviewing the previous content and learning algorithms, so I did not continue to learn new knowledge, so I stopped for a longer period of time and formally returned to learn new knowledge from today!

Filter: Filter

  1. Concepts:
  • Life's filters: water purifiers, air purifiers, bandits,
  • Filters in the web: When accessing a server's resources, filters can intercept requests and perform special functions.
  • Functions of the filter:
  • Usually used to complete common operations.For example: login validation, uniform encoding processing, sensitive character filtering...
  1. Quick Start:
    1. Steps:
      1. Define a class to implement the interface Filter
      2. Replication Method
      3. Configure Interception Path
        1. web.xml
        2. annotation
  2. Code:
@WebFilter("/*")//This filter is executed before all resources are accessed
  public class FilterDemo1 implements Filter {
      @Override
      public void init(FilterConfig filterConfig) throws ServletException {
  
      }
  
      @Override
      public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
          System.out.println("filterDemo1 Executed....");
            //Release
          filterChain.doFilter(servletRequest,servletResponse);
  
      }
  
      @Override
      public void destroy() {
  
      }
  }
  1. Filter details:
    1. web.xml configuration
<filter>
         <filter-name>demo1</filter-name>
         <filter-class>cn.itcast.web.filter.FilterDemo1</filter-class>
     </filter>
     <filter-mapping>
         <filter-name>demo1</filter-name>
   <!-- Intercept Path -->
         <url-pattern>/*</url-pattern>
     </filter-mapping>
  1. Filter Execution Process
    1. Execute filter
    2. Post-release resources
    3. Go back and execute the code below the filter release code
  2. Filter life cycle approach
    1. Init: After the server starts, a Filter object is created and the init method is called.Execute only once.For loading resources
    2. doFilter: Executes each request when a resource is intercepted.Execute multiple times
    3. Destroy: The Filter object was destroyed after the server was shut down.If the server shuts down normally, the destroy method is executed.Execute only once.Used to release resources
  3. Detailed filter configuration
  • Intercept path configuration:
    1. Specific resource path: /index.jsp The filter will only be executed if 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 accesses all suffix-named JSP resources and the filter is executed
    4. Intercept all resources: /* When accessing all resources, the filter will be executed
  • Intercept configuration: how resources are accessed
  • Note Configuration:
  • Set dispatcherTypes property
    1. REQUEST: Default value.Browser requests resources directly
    2. FORWARD: Forward access to resources
    3. INCLUDE: Contains access resources
    4. ERROR: Error jumping resources
    5. ASYNC: Asynchronous access to resources
  • web.xml configuration
  • Set <dispatcher></dispatcher>tab
  1. Filter chain (configuring multiple filters)
  • Execution order: If there are two filters: filter 1 and filter 2

    1. Filter 1
    2. Filter 2
    3. Resource Execution
    4. Filter 2
    5. Filter 1
  • Question of filter order:

    1. Annotation Configuration: Compare by string comparison rule of class name, small value is executed first
      *For example: AFilter and BFilter, AFilter executes first.
    2. web.xml Configuration: Who Defines Above and Who Executes First
  1. Case:
    1. Case 1_Logon Verification
      • Requirements:
        1. Access resources for the day17_case case.Verify that it is logged on
        2. If you are logged in, you will be released directly.
        3. If you are not logged in, jump to the login page and prompt "You are not logged in, please log in first".

package cn.itcast.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Logon Authentication Filter
 */
@WebFilter("/*")
public class LoginFilter implements Filter {


    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println(req);
        //0. Cast
        HttpServletRequest request = (HttpServletRequest) req;

        //1.Get Resource Request Path
        String uri = request.getRequestURI();
        //2.Determine if login-related resource paths are included,Be careful to exclude css/js/picture/Resources such as Authentication Codes
        if(uri.contains("/login.jsp") || uri.contains("/loginServlet") || uri.contains("/css/") || uri.contains("/js/") || uri.contains("/fonts/") || uri.contains("/checkCodeServlet")  ){
            //Yes, the user just wants to log in.Release
            chain.doFilter(req, resp);
        }else{
            //Not included, need to verify user logon
            //3.From Get session Get in user
            Object user = request.getSession().getAttribute("user");
            if(user != null){
                //Logged in.Release
                chain.doFilter(req, resp);
            }else{
                //Not logged in.Jump to login page

                request.setAttribute("login_msg","You are not logged in yet, please log in");
                request.getRequestDispatcher("/login.jsp").forward(request,resp);
            }
        }


        // chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

    public void destroy() {
    }

}
  1. Case 2 Sensitive Word Filtering
  • Requirements:

    1. Sensitive vocabulary filtering for data entered in day17_case
    2. Sensitive Vocabulary Reference Sensitive Vocabulary.txt
    3. If sensitive, replace with ***
  • Analysis:

    1. Enhance the request object.Enhanced acquisition parameter related methods
    2. Release.Delivery Proxy Object
  • Enhance the functionality of the object:

    • Design patterns: some common ways to solve fixed problems
    1. Decoration Mode
    2. proxy pattern
    • Concepts:
    1. Real object: the object being proxied
    2. Proxy object:
    3. Proxy mode: Proxy objects proxy real objects to enhance the function of real objects
    • Implementation:
      1. Static Proxy: There is a class file describing the proxy mode
      2. Dynamic proxy: Form proxy classes in memory
    • Steps to achieve:
      1. Proxy objects and real objects implement the same interface
      2. Proxy object= Proxy.newProxyInstance();
      3. Call a method using a proxy object.
      4. Enhancement Method

Agent conceptual analysis: Code implementation:
package cn.itcast.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

/**
 * Sensitive Vocabulary Filter
 */
@WebFilter("/*")
public class SensitiveWordsFilter implements Filter {


    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //1. Create proxy objects to enhance getParameter methods

        ServletRequest proxy_req = (ServletRequest) Proxy.newProxyInstance(req.getClass().getClassLoader(), req.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //Enhance getParameter Method
                //Determine whether it is getParameter Method
                if(method.getName().equals("getParameter")){
                    //Enhanced Return Value
                    //Get Return Value
                    String value = (String) method.invoke(req,args);
                    if(value != null){
                        for (String str : list) {
                            if(value.contains(str)){
                                value = value.replaceAll(str,"***");
                            }
                        }
                    }

                    return  value;
                }

                //Determine if the method name is getParameterMap

                //Determine if the method name is getParameterValue

                return method.invoke(req,args);
            }
        });

        //2.Release
        chain.doFilter(proxy_req, resp);
    }
    private List<String> list = new ArrayList<String>();//Sensitive Vocabulary Collection
    public void init(FilterConfig config) throws ServletException {

        try{
            //1.Get the true path to the file
            ServletContext servletContext = config.getServletContext();
            String realPath = servletContext.getRealPath("/WEB-INF/classes/Sensitive vocabulary.txt");
            //2.read file
            BufferedReader br = new BufferedReader(new FileReader(realPath));
            //3.Add each row of data to the file list in
            String line = null;
            while((line = br.readLine())!=null){
                list.add(line);
            }

            br.close();

            System.out.println(list);

        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public void destroy() {
    }

}

Listener: Listener

  • Concept: One of the three components of the web.
    • Event monitoring mechanism
    • Event: One thing
    • Event source: where the event occurred
    • Listener: an object
    • Register listeners: Bind events, event sources, and listeners together.Execute listener code when an event occurs on the event source
  • ServletContextListener: Listens for creation and destruction of ServletContext objects
    • Method:
    • void contextDestroyed(ServletContextEvent sce): This method is called before the ServletContext object is destroyed
    • void contextInitialized(ServletContextEvent sce): This method is called when a ServletContext object is created
  • Steps:
  1. Define a class to implement the ServletContextListener interface
  2. Replication Method
  3. To configure
    1. web.xml
  <listener>
    <listener-class>cn.itcast.web.listener.ContextLoaderListener</listener-class>
  • Specify initialization parameters
  1. Notes:
    • @WebListener
31 original articles were published, 4 were praised, and 868 were visited
Private letter follow

Topics: Java JSP xml encoding