SpringMVC Filters use parsing, springmvcfilter

Source: Internet
Author: User

SpringMVC Filters use parsing, springmvcfilter

SpringMVC framework is a mature and excellent java web development framework. Learning and researching framework design helps us better understand and master spring MVC, and design and write more suitable structures and code.

This section describes how to set a filter in the SpringMVC framework and uses the encoding processing filter as an example to learn how to set a filter in the framework.

 

 

As shown in the spring-web.jar package structure above, Spring web packages provide many filters that are located at org. springframework. web. filter and, of course, implement javax. servlet. Filter,

However, there are several implementation methods::

(1) Implement Filter directly. Only CompositeFilter is used for this type of Filter;

(2) inherit from the abstract class GenericFilterBean, which implements javax. servlet. Filter. There is only one Filter, namely DelegatingFilterProxy;

(3) inherit from the abstract class OncePerRequestFilter, which is a direct subclass of GenericFilterBean. These filters include CharacterEncodingFilter, HiddenHttpMethodFilter, HttpPutFormContentFilter, RequestContextFilter, and ShallowEtagHeaderFilter;

(4) inherit from the abstract class AbstractRequestLoggingFilter, which is the direct subclass of OncePerRequestFilter. These filters include CommonsRequestLoggingFilter, Log4jNestedDiagnosticContextFilter and ServletContextRequestLoggingFilter.

Where is the filter placed in the container structure?

Before placing a filter on a web resource, you can intercept the access request before the request reaches the web resource of the application (a Servlet, a Jsp page, or even an HTML page, and the output request is intercepted before it returns to the customer. Filter: Used to intercept requests. It is between the client and the requested resource and is used to reuse code. Filter chain, which is configured first in web. xml and called first. You can also configure initialization parameters in the filter.

The Filter in Java is not a standard Servlet. It cannot process user requests or generate responses to clients. It is mainly used to pre-process HttpServletRequest or HttpServletResponse. It is a typical processing chain.

FilterThere are several types:

L user-authorized Filter: The Filter checks user requests and filters illegal user requests according to requests.

L LOG Filter: records some special user requests in detail.

L Filter responsible for decoding: including decoding requests for non-standard encoding.

L it can change the tfilter of XML content.

 

FilterIt has the following functions::

L intercept the customer's HttpServletRequest before HttpServletRequest arrives at the Servlet.

L check HttpServletRequest as needed, or modify the HttpServletRequest header and data.

L intercept HttpServletResponse before HttpServletResponse arrives at the client.

L check HttpServletResponse as needed. You can modify the HttpServletResponse header and data.

 

CreateFilterOnly two steps are required.:
(1) create a Filter processing class:

(2) Configure Filter in the web. xml file.

 

To create a Filter, you must implement the javax. servlet. Filter interface, which defines three methods.
• Void init (FilterConfig config): used to initialize the Filter.
• Void destroy (): Used to recycle certain resources before the Filter is destroyed.
• Void doFilter (ServletRequest request, ServletResponse response, FilterChainchain): implements the filter function. This method is used to add additional processing for each request and response.

The Filter also has a lifecycle: init ()-> doFilter ()-> destroy (), which is driven by the filter element in the deployment file.

Refer to the encoding filter example to see how to implement

<! -- Encoding processing filter --> <filter-name> encodingFilter </filter-name> <filter-class> org. springframework. web. filter. characterEncodingFilter </filter-class> <init-param> <param-name> encoding </param-name> <param-value> UTF-8 </param-value> </init- param> <init-param> <param-name> forceEncoding </param-name> <param-value> true </param-value> </init-param> </filter> <filter-mapping> <filter-name> encodingFilter </filter-name> <url-pattern> *. do </url-pattern> </filter-mapping>

 

Among them, the filter-class is the Filter class, And the init-prama is the set parameter of the injection.

The url-pattern in Filter-mapping is the filtered url type.

 

Class inheritance relationship

CharacterEncodingFilterThe r class inheritsOncePerRequestFilterClass

Public class CharacterEncodingFilter extends OncePerRequestFilter

 

WhileOncePerRequestFilterThe class inheritsGenericFilterBeanClass

Public abstract class OncePerRequestFilter extends GenericFilterBean

 

Public abstract class GenericFilterBean implements

Filter, BeanNameAware, EnvironmentAware, ServletContextAware, InitializingBean, DisposableBean

 

 

Set the encoding core code

@Override   protected void doFilterInternal(         HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)         throws ServletException, IOException {       if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {         request.setCharacterEncoding(this.encoding);         if (this.forceEncoding) {            response.setCharacterEncoding(this.encoding);         }      }      filterChain.doFilter(request, response);   } 

 

 

FilterChain is the filter chain, indicating that the next filter is executed after the filter is executed.

Differences

When we use filters, we usually do not need to know the GenericFilterBean, OncePerRequestFilter, and filters, but it does not affect our understanding of these classes. As mentioned above, tokens inherit from OncePerRequestFilter and OncePerRequestFilter inherit from GenericFilterBean, therefore, we know that genericFilterBean is a convenient superclass for any type of filter. This class mainly implements from the web. get the value set in init-param in the xml file and initialize the Filter (of course, its subclass can overwrite the init method ).

OncePerRequestFilter inherits from GenericFilterBean, so it naturally knows how to obtain the attributes and values in the configuration file. Therefore, the focus is not on the values, but on ensuring that after a request is received, each filter is executed only once. Its subclass only needs to focus on the specific implementation of the Filter, that is, doFilterInternal.

AbstractRequestLoggingFilter is an extension of OncePerRequestFilter. In addition to inheriting all functions of its parent and ancestor classes, it also determines the events executed before and after filtering in doFilterInternal, its subclass focuses on beforeRequest and afterRequest.

In general, these three classes perform a certain part of the Filter function respectively. Of course, the specific implementation is defined by their subclass. If you need to implement your own Filter, you can also inherit the classes you need according to the above descriptions.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.