当前位置:网站首页>Filter filter

Filter filter

2022-06-27 08:07:00 2022 come on

Catalog

         One 、 What is? Filter filter ?

         Two 、 Application, for example,  

         3、 ... and 、 To use a filter

         Four 、Filter Life cycle of

         5、 ... and 、FilterConfig class

         6、 ... and 、FilterChain class

         7、 ... and 、Filter The interception path of

          8、 ... and 、 ThreadLocal Introduction to


One 、 What is? Filter filter ?

  When the browser sends a request to the server to browse a resource , First of all, it will go through Filter filter , Determine whether the permission is met

1Filter Filter it's JavaWeb One of the three components of . The three components are :Servlet Program 、Listener Monitor 、Filter filter  

2Filter Filter it's JavaEE The specification of . That's the interface
3Filter The function of the filter is : Intercept request , Filtering response .
Common application scenarios for intercepting requests are :
1、 Permission check
2、 Diary operation
3、 Business management
…… wait

Two 、 Application, for example,  

Suppose we were web There is a admin Catalog , There are some resources 【 picture ,html, page ....】 , We want to log in to access , Jump to the login interface without logging in .

So according to what we learned before : It should be when the login is successful , take user Save to session domain , When jumping resources , Judge session Whether the user in the domain is empty , If it is empty, it means that you have not logged in yet , Then jump to the login interface . If it is not empty, you can access resources .

    <%
        /* Judge , If user It's empty , Then go to the login page .*/
        Object user = session.getAttribute("user");
        if (user == null){
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }
    %>

  When we visit jsp When the page is , If he doesn't log in, he will jump to the login page .

  When we are not logged in , Still have access to a.html The page also has pictures , So this method has limitations .

 

It can only be jsp On the page ,html, Pictures cannot be judged session Whether the domain is empty . So we need to use   Filter filter .

  3、 ... and 、 To use a filter

1、 Write a class implementation javax.servlet.Filter Interface , And realize Filter Three methods in the interface .init,doFilter,destroy .

2、 stay doFilter In the method , Write the interception operation .

@Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //
        HttpServletRequest request  = (HttpServletRequest) servletRequest;
        Object user = request.getSession().getAttribute("user");
        if (user == null){
            // Intercept operation : If user It's empty , No sign in .
            // Jump to the login screen servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
            return;
        }else{
            // Can access resources 
            // Which resources can be accessed , stay  web.xml  Configuration in file 
            //  This code is very important , If you do not write, you will not be able to access any resources even if you log in successfully .
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

3、 stay web.xml Configure which resources can be accessed in the file . And configuration Servlet similar .

The intercepted path can write multiple addresses . 

    <filter>
        <!-- to  filter  Make up an alias -->
        <filter-name>FilterTest</filter-name>
        <!-- Full class name -->
        <filter-class>yangzhaoguang.FilterTest</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>FilterTest</filter-name>
        <!--
             Configure interception path :
                / :  Express :http;//ip:port/ Project path /
                /admin/* :  Said to admin All resources under the directory are intercepted .
        -->
        <url-pattern>/admin/*</url-pattern>
        <url-pattern>/admin/b.jsp</url-pattern>
    </filter-mapping>

At this time we are visiting admin Resources under : Can be intercepted . If you can still access resources , It means that the browser also has a cache , Just clean it up .

  The above is the case of successful interception without login , The following shows how to log in successfully , Can you access .

Provide a login page and LoginServlet :

<form action="/filter/loginServlet" method="post">
 user name :<input type="text" name="username" ><br>
 password :<input type="password" name="password" ><br>
    <input type="submit" value=" Sign in ">
</form>
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");


        if ("admin".equals(username) && "admin".equals(password)){
            // Login successful , Save user information to  session  domain 
            request.getSession().setAttribute("user",username);
            request.getRequestDispatcher("/login_success.jsp").forward(request,response);
        }else{
            // No login success , Call back to the login interface 
            request.getRequestDispatcher("/login.jsp").forward(request,response);

        }
    }
}

  After successful login ,admin All resources under can be accessed , There is no problem .

  Four 、Filter Life cycle of

Be similar to Servlet Medium init ,service ,destroy Method .

Filter The life cycle of is composed of several methods
1、 Constructor method
2init Initialization method
         The first 1,2 Step , stay web When the project starts (Filter Created )
3doFilter Filtration method
         The first 3 Step , Every time a request is intercepted , Will execute
4destroy The destruction
         The first 4 Step , stop it web During the project , Will execute ( stop it web engineering , It will be destroyed Filter filter )

 

5、 ... and 、FilterConfig class

FilterConfig The name and meaning can be seen by category , It is Filter Filter profile class .
Tomcat Each creation Filter When , It will also create a FilterConfig class , It contains Filter Configuration information of the configuration file .
        
        
        <!-- stay  filter  In the label , To configure FilterConfig Parameters .-->
        <init-param>
            <param-name>name1</param-name>
            <param-value>value1</param-value>
        </init-param>
        <!-- You can also configure multiple -->
        <init-param>
            <param-name>name2</param-name>
            <param-value>value2</param-value>
        </init-param>
FilterConfig The role of a class is to get filter Filter configuration content
        1、 obtain Filter The name of filter-name The content of , Is in the web.xml Alias in file .
filterConfig.getFilterName()
        2、 To get in Filter Configured in init-param Initialize parameters
filterConfig.getInitParameter("name")
        3、 obtain ServletContext object
filterConfig.getServletContext()

  Get parameters during initialization :

 @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("2 init Initialize method execution ");
//         1、 obtain  Filter  The name of  filter-name  The content of 
        System.out.println(" obtain  filter-name:"+ filterConfig.getFilterName());
//         2、 To get in  Filter  Configured in  init-param  Initialize parameters 
        System.out.println("init-param Medium  name1  Of value" + filterConfig.getInitParameter("name1"));
        System.out.println("init-param Medium  name2  Of value" + filterConfig.getInitParameter("name2"));
//         3、 obtain  ServletContext  object 
        System.out.println("ServletContext object :"+filterConfig.getServletContext());

    }

  6、 ... and 、FilterChain class

FilterChain It's the filter chain ( How multiple filters work together )

We can see that the execution sequence is the same as that in the figure

1、 The order in which multiple filters are executed is determined by web.xml It's decided by the document , Which filter should be configured first , Which filter will execute first .

If you configure first Filter2 .

  First configure Filter2,Filter2 It will be executed first .

2、 Filter in by filterChain.doFilter(); To continue accessing the next resource , Without this code , Later resources will not be accessed , The code will not be executed .

take Filter1 Medium  filterChain.doFilter() Get rid of , So the back Filter2 and b.jsp The page will not execute to .

3、 It can also be seen from the picture , The whole process is completed in one request , That is, they share the same request domain . 

7、 ... and 、Filter The interception path of

-- Exactly match
<url-pattern>/target.jsp</url-pattern>
The path of the above configuration , Indicates that the request address must be :http://ip:port/ Project path /target.jsp
-- Directory matching
<url-pattern>/admin/*</url-pattern>
The path of the above configuration , Indicates that the request address must be :http://ip:port/ Project path /admin/*
-- Suffix matches
<url-pattern>*.html</url-pattern>
The path of the above configuration , Indicates that the request address must be in .html The end will intercept
<url-pattern>*.do</url-pattern>
The path of the above configuration , Indicates that the request address must be in .do The end will intercept
<url-pattern>*.action</url-pattern>
The path of the above configuration , Indicates that the request address must be in .action The end will intercept
Filter The filter only cares about whether the requested address matches , Does not care if the requested resource exists !!!

8、 ... and 、 ThreadLocal Introduction to

ThreadLocal yes JDK A class in ,ThreadLocal Commonly referred to as Thread local variable , It's a special thread binding mechanism , Put the variable 【( It can be a normal variable , It can be the object , It can also be an array , aggregate 】 With threads binding together , Maintain an independent copy of variables for each thread . adopt ThreadLocal You can limit the visibility of an object to the same thread .

ThreadLocal Characteristics :
        1、ThreadLocal You can associate a data for the current thread . If you associate multiple data , The following data will overwrite the previous data , image map In the collection key repeat ,value Will be covered ( It can look like Map And access data ,key Is the current thread
        2、 every last ThreadLocal object , Only one data can be associated for the current thread , If you want to associate multiple data for the current thread , You need to use multiple ThreadLocal Object instances .
        3、 Every ThreadLocal When an object instance is defined , It's usually static type
        4、ThreadLocal Save data in , After the thread is destroyed . Will be JVM Virtual auto release .

And synchronized The relationship between :

Some articles take ThreadLocal and synchronized Compare , In fact, their realization ideas are different .

  • synchronized At most one thread can execute at the same time , So only one copy of the variable needs to be saved , It is a kind of thought that time changes space
  • ThreadLocal Multiple threads do not affect each other , So each thread stores a variable , It is a kind of space for time
Construction method summary
ThreadLocal()
           Create a thread local variable .
 Tget()
          Get the variable value in the current thread pool
 voidremove()
           Remove the value of the current thread from this thread local variable .
 voidset(T value)
          Deposit in Thread pool The variable value of is value

  Use ThreadLocal No need to set key Value ,key Is the name of the current thread .

public class ThreadLocalTest {
    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            // Create multiple threads 
            new Thread(new Task()).start();
        }
    }

    /* <>  refer to  value The type of */
    public  static ThreadLocal<Object> threadLocal = new ThreadLocal<>();
    private static Random random = new Random();

    // Create a thread task 
    public static class Task implements Runnable {
        @Override
        public void run() {
            // Get the name of the current thread 
            String name = Thread.currentThread().getName();
            // Get a random number 
            int i = random.nextInt(200);
            //  Match the current thread with   A value   Related to .
            threadLocal.set(i);
            System.out.println(" Save thread [ " + name + " ]  The value of the Association :" + threadLocal.get());

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // Take out the associated value 
            System.out.println(" Take out the thread [ " + name + " ]  The value of the Association :" + threadLocal.get());
        }
    }
}

We can see ThreadLocal Not only is it safe , And it does not affect the use of multiple threads . And each thread will save a variable . 

原网站

版权声明
本文为[2022 come on]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202161659109301.html