The use of javaee OA project filter to solve the filter of Chinese random code and use the filter to realize interception and judgment

Why use filters

What are the problems we have encountered in our current writing project?

A. The advantage of baseServlet currently used is that it is convenient to handle garbled code uniformly. However, if we do not use servlet in the future, we need to write in each servlet when dealing with Chinese garbled code, but it is more troublesome.
B. In the process of login interception, we need to write the interception code repeatedly in each page, which will become very troublesome.

  The final problem: repeated code is written many times in the project. 
  Solution: filter

What is a filter?

When does the filter go in the code

We enter an address in the browser. If there is no filter in the project, we will directly access the servlet. However, if we configure the filter and set which path access needs to go through the filter, as long as the browser enters an address and the filter is also configured in the project. Once the corresponding path is accessed, the project will automatically go through the filter first, and then the servlet layer

How to use filters in a project

First create a filter (a filter to solve Chinese garbled code)

Configure this filter into the project

The filter created by yourself needs to be combined with the project, so it needs to be configured, so it is on the web Just configure it in XML.

As soon as the browser enters an address, the first thing to visit is the web XML file. On the web XML goes from top to bottom.

summary

Now to solve the problem of Chinese garbled code, let's go to the web A global attribute can be set in XML, and then the global attribute can be obtained in the code to realize decoupling.

The first step is on the web Set global attributes in XML

    <context-param>
        <param-name>enc</param-name>
        <param-value>utf-8</param-value>
    </context-param>

The second step is to create a filter to solve global garbled code


The code inside is

package com.filter;

import javax.servlet.*;
import java.io.IOException;

public class EncFilter implements Filter {

    private  String enc2;

    //Initialization method -- execute once
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        //Read initialization parameters
         enc2 = filterConfig.getInitParameter("enc2");

         //Global parameters
        String enc = filterConfig.getServletContext().getInitParameter("enc");
    }

    //Service request -- > every request will be executed
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {


        //[A] Preprocessing operations before reaching the target resource

         req.setCharacterEncoding(enc2);

        //[B] Execute the next filter or target resource

        chain.doFilter(req,resp);

        //[C] Processing operations before leaving the server

    }

    //Destruction method -- specify once
    @Override
    public void destroy() {

    }
}

Step 3: Web XML

      <filter>
          <filter-name>EncFilter</filter-name>
          <filter-class>com.filter.EncFilter</filter-class>
          <init-param>
              <param-name>enc2</param-name>
              <param-value>utf-8</param-value>
          </init-param>
      </filter>

      <filter-mapping>
          <filter-name>EncFilter</filter-name>
          <!--Filter path: what path will pass through the filter-->
          <url-pattern>/uu/*</url-pattern>
      </filter-mapping>

The above is how to use filters in the project.

How to use filter to realize interception judgment

First create a filter that implements interception


The code inside

package com.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter  implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

          //Get the content saved to the session
       HttpServletRequest  req=  (HttpServletRequest)request;

       HttpServletResponse  resp=(HttpServletResponse)response;

        Object emp = req.getSession().getAttribute("emp");


        //Get the current login path of the user. If the login path is login JSP direct release. If it's not filtering

        //   /login.jsp
        String uri = req.getRequestURI();

        //Parameter method=login after obtaining the path
        String queryString = req.getQueryString();

        if("/login.jsp".equals(uri)||"/EmployeeServlet?method=login".equals(uri+"?"+queryString)){

            chain.doFilter(req,resp);
        }else {

            if(emp!=null){
                //Prove that the user is logged in
                chain.doFilter(req,resp);
            }else {
                resp.sendRedirect(req.getContextPath()+"/login.jsp");
                return;
            }
        }
    }

    @Override
    public void destroy() {

    }
}

On the web Configure this filter in XML

<filter>
    <filter-name>LoginFilter</filter-name>
    <filter-class>com.filter.LoginFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <url-pattern>*.jsp</url-pattern>
    <url-pattern>*.html</url-pattern>
    <url-pattern>/com/*</url-pattern>
</filter-mapping>

The above configuration is complete

Filter more

Question 1: how to determine the execution order of multiple filters?

The order of execution determines the order of execution

Let's create two filters first

package com.filter;

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

public class Filter1  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("--Filter1--befor");

        filterChain.doFilter(servletRequest,servletResponse);

        System.out.println("--Filter1--After");


    }

    @Override
    public void destroy() {

    }
}

package com.filter;

import javax.servlet.*;
import java.io.IOException;

public class Filter2  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("--Filter2--befor");

        filterChain.doFilter(servletRequest,servletResponse);

        System.out.println("--Filter2--After");


    }

    @Override
    public void destroy() {

    }
}

On the web Configure these two filters in XML. Just visit login JSP page, then go to the filter, then which one to go first?

We visit login JSP page, which filter to go first?


According to the output results, we can see

When there are multiple filters, the filter to be used is related to this order

Question 2: does every request and response go through a filter?

No, whether to pass through the filter depends on the path of the filter;
/servlet/ /

Question 3: do you execute the filter code from beginning to end when requesting and responding

no Perform pre-processing operation when requesting and post-processing operation when responding;
If the execution order of the filter is 1,2,4 when requesting, the execution order of the filter is 4,2,1 when responding

Question 4: can I jump to any other resources of the project in the filter

sure
For example: if a filter is for permission verification and there is no login, it will not allow access to the target resource and directly jump to login jsp

Question 5: are redirects and forwards filtered

Redirect through
The default forwarding does not go through, because it is a server-side jump. It can be solved by configuration

Keywords: filter

Added by Full-Demon on Mon, 31 Jan 2022 12:38:00 +0200