java Filter "suggestions collection"

Hello, everyone. Meet you again. I'm your friend Quan Zhanjun.

1, Introduction

The Filter in Servlet implements javax Servlet. The server-side program of the Filter interface is mainly used to Filter character codes and make some business logic judgments, such as whether you have permission to access pages. It works as long as you are on the web The XML file configures the client requests to be intercepted, and it will help you intercept the requests. At this time, you can uniformly set the encoding for the Request or response (Request and Response) to simplify the operation; At the same time, it can also make logical judgments, such as whether the user has logged in, whether he has permission to access the page, and so on. It starts with the start of your web application. It is initialized only once, and relevant requests can be intercepted later. It is destroyed only when your web application is stopped or redeployed. The following code examples are used to understand its use.

2, Instance

package test.filter; 
import ...; 
/**
 * Introduce the use of filter, taking setting code as an example
 */
public class MyFilter implements Filter { 
  private FilterConfig config = null; 
  private boolean isFilter = false;
  
  public void destroy() { 
   System.out.println("MyFilter Prepare for destruction..."); 
  } 
  
  public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOException, ServletException { 
   // Cast type 
   HttpServletRequest request = (HttpServletRequest)arg0; 
   HttpServletResponse response = (HttpServletResponse)arg1; 
   // Get web The code set set set by XM is set in Request and Response   
   request.setCharacterEncoding(config.getInitParameter("charset"));   
   response.setContentType(config.getInitParameter("contentType"));   
   response.setCharacterEncoding(config.getInitParameter("charset"));   
   // Forward the request to the destination to continue execution
   chain.doFilter(request, response);
  } 
  
  public void init(FilterConfig arg0) throws ServletException { 
   this.config = arg0; 
   if(isFilter){
      System.out.println("MyFilter initialization..."); 
   }
  } 
  
  private void setIsFilter(boolean isFilter){
	this.isFilter = isFilter;
  }
}
copy

Then on the web Configure the filter in the XML:

 <filter>
 	<filter-name>MyFilter</filter-name>
 	<filter-class>test.filter.MyFilter</filter-class>
 	<init-param>
 		<param-name>isFilter</param-name>
 		<param-value>true</param-value>
 	</init-param>
 </filter>
 <filter-mapping>
 	<filter-name>MyFilter</filter-name>
 	<url-pattern>/*</url-pattern>
 	<dispatcher>REQUEST</dispatcher> <!-- No configuration dispatcher Is the default request Methodical -->
 	<dispatcher>FORWARD</dispatcher>
 	<dispatcher>ERROR</dispatcher>
 	<dispatcher>INCLUDE</dispatcher>
 </filt
copy

3, Detailed introduction

What is usually done in the doFilter method? Here are some examples:

1. Control the chain Call the method of dofilter to determine whether to access the target resource.

For example, you can verify the user permissions. Judge whether the user has permission to access some resources. If the user has permission to release, he will not execute the chain Dofilter method. 2. When calling chain Before the dofilter method, do some processing to achieve some purposes. For example, solve the problem of Chinese garbled code and so on. You can set the encoding of the request and response before the doFilter method. You can even encapsulate and decorate the request interface to deal with the Chinese garbled code in the get request mode (rewrite the corresponding request.getParameter method). 3. When calling chain After the dofilter method, do some processing to achieve some purposes. For example, compress the entire web site. When calling chain The dofilter method used class A to encapsulate and decorate the response object, overriding getOutputStream and getWriter methods. Inside class A, cache the output content into the ByteArrayOutputStream stream stream, and then in the chain After the dofilter method is executed, the ByteArrayOutputStream cache data in class A is obtained and compressed with the GZIPOutputStream stream stream.

Filter can not only specify which url matching resources to intercept through url pattern. In addition, you can also specify which specific servlet to intercept through servlet name (specifically for a servlet, and servlet name corresponds to the relevant configuration of the servlet).

The dispatcher in the Filter mapping tag specifies how the resources intercepted by the Filter are called by the Servlet container. It can be one of REQUEST,INCLUDE,FORWARD and ERROR. The default is REQUEST. The user can set multiple <dispatcher> sub elements to specify the Filter to intercept multiple calls to resources.

REQUEST:

When the user directly accesses the page, the Web container invokes the filter. If the target resource is accessed through the include() or forward() methods of the RequestDispatcher or in the ERROR case, the filter will not be called.

INCLUDE:

If the target resource is accessed through the include() method of RequestDispatcher, the filter will be called. Otherwise, the filter will not be called.

FORWARD:

If the target resource is accessed through the forward() method of RequestDispatcher, the filter will be called. Otherwise, the filter will not be called.

ERROR:

If the error attribute =examerror JSP, if an exception occurs in A.jsp, it will jump to examerror JSP. And jump to examerror JSP, if the filter is configured with an error dispatcher, it will be intercepted, otherwise it will not be intercepted.

4, Advanced configuration (allow proxy to inject spring beans)

web. Configure filter DelegatingFilterProxy in XML:

<filter>
    <filter-name>permission</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
        <param-name>targetFilterLifecycle</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
 <filter-mapping>
    <filter-name>permission</filter-name>
    <url-pattern>*.htm</url-pattern>
</filter-mapping>
copy

Add the following to the spring bean configuration:

<bean id="permission" class="Yours bean"></bean>
copy

The id of the bean must be the same as filter name. If you want to be different, you can configure it as follows:

<filter>
    <filter-name>permission</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
     <init-param>
        <param-name>targetFilterLifecycle</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>targetBeanName</param-name>
        <param-value>test</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>permission</filter-name>
    <url-pattern>*.htm</url-pattern>
</filter-mapping>
copy

Add the following to the spring bean configuration:

<bean id="test" class="Yours bean"></bean>
copy

Your spring bean above must implement the Filter interface.

So what's this for?

A: in this way, the filter proxied by DelegatingFilterProxy can be used as a spring bean and managed by spring. That is, the lifecycle of the filter can be managed through the spring container. In addition, if some instances of the spring container are required in the filter, it can be directly injected through spring. In addition, some configuration files can be read. These convenient operations can be configured and implemented through spring.

If "targetfilterlife" is set to True, then filter Init() and filter Destroy() is valid; If false, both methods fail.

If you use Shiro (a powerful and easy-to-use Java security framework that performs authentication, authorization, cryptography, session management, etc.), you will usually use this DelegatingFilterProxy!

Publisher: full stack programmer stack length, please indicate the source for Reprint: https://javaforall.cn/133012.html Original link: https://javaforall.cn

Posted by elToro on Thu, 30 Jun 2022 17:53:22 +0530