Org.springframework.web.filter.CharacterEncodingFilter.

Source: Internet
Author: User
Tags abstract character set constant

Thank you: http://blog.csdn.net/heidan2006/article/details/3075730


Very simple and useful a filter, the current JSP page and Java code using a different character set to encode the data will appear when the form submitted or upload/download Chinese name file garbled problem, then this class can appear.

From the name can be seen that it is a filter, so it is necessary to configure the normal filter as configured in the Web. XML, configured as follows: <filter> <filter-name>encodingfil Ter</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>false</param-value> </init-param></filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

And ordinary filter configuration is no different, that is, two more initialization parameters, the role of two parameters are:

Encoding-----> used to specify a specific character set

Forceencoding-------Earlier versions of >spring This parameter is very simple, and if a character set is already specified in the request, will it be set to the request using the endcoding corresponding to the character set. For example, if the filter is configured to Web. Xml as above, when the request is committed, the filter will determine if request.getcharacterencoding () is null. If it is null then the request.setcharacterencoding ("UTF-8") operation will be performed, and if not NULL then the filter will not do anything.

But spring's current version of this class of code has been refactored, the code is more "Beautiful", the role of this parameter has also undergone a slight change.

In order to deepen the impression from the source code to analyze the change of this parameter.

     First, the description   Characterencodingfilter is inherited Onceperrequestfilter abstract class, Onceperrequestfilter implements the DoFilter method:  public final void dofilter (Servletrequest request,  servletresponse response, filterchain filterchain)    throws  Servletexception, ioexception {        &nbsp, ...... &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP,       string, ... and so on.  alreadyfilteredattributename = getalreadyfilteredattributename ();       if  (Request.getattribute (alreadyfilteredattributename)  !=  null | |  shouldnotfilter (HttpRequest))  {            Filterchain.dofilter (Request, response);       }       else {       &Nbsp;    request.setattribute (alreadyfilteredattributename, boolean.true);        try {             dofilterinternal (Httprequest, httpresponse, filterchain);            }         finally {            request.removeattribute ( Alreadyfilteredattributename);            }          } public static final string already_filtered_suffix =  ". FILTERED "; (constants defined in Onceperrequestfilter)

Description

1. The string returned by the Getalreadyfilteredattributename () method is = "We give the filter the name +already_filtered_suffix configuration", So the request requests the first time the filter is reached Request.getattribute (alreadyfilteredattributename) value must be null, Shouldnotfilter (HttpRequest) The default implementation of the method always returns False (this method can also be extended within subclasses);

2. When Request.setattribute (Alreadyfilteredattributename, boolean.true) executes dofilterinternal (HttpRequest, HttpResponse, Filterchain); method, Dofilterinternal here is an abstract method, which is implemented in the subclass Characterencodingfilter, implemented as follows: 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 && responsesetcharacterencodingavailable)  {                      Response.setcharacterencoding (this.encoding);                     }                               filterchain.dofilter (Request, response) ;   } private final static boolean responsesetcharacterencodingavailable =&nbSp Classutils.hasmethod (   HttpServletResponse.class,  "setcharacterencoding", new  Class[] {string.class});

Description

1. Static constant responsesetcharacterencodingavailable is the reflection to determine whether response has setcharacterencoding method, the return value should be true.

2. this.encoding! = null: The condition is satisfied when the encoding initialization parameter is specified.

3. (This.forceencoding | | request.getcharacterencoding () = null) ==true: The condition is satisfied when the Forceencoding initialization parameter is set to TRUE or the request has been specified with a character encoding.

If not, spring's earlier version of this method should be implemented as follows: protected void dofilterinternal (HttpServletRequest request, HttpServletResponse Response, Filterchain Filterchain) throws Servletexception, IOException {if (this.forceencoding | | request.ge               tcharacterencoding () = = null) {request.setcharacterencoding (this.encoding);   } filterchain.dofilter (request, response); }

The function of parameter forceencoding is obvious. Previously just worked on the request character encoding, now if setting forceencoding to true also affects the character encoding in response, which is often not what we want.

Summarize:

1. Onceperrequestfilter This abstract filter is a good implementation of only one filter per request, if there is a similar requirement can inherit the class and implement the Dofilterinternal method to complete.

2. The Characterencodingfilter class can help us to implement character set conversion through simple configuration. In addition, if you use the STRUTS2.0 MVC framework I personally feel that the Chinese problem is not a problem, you can configure the struts.i18n.encoding constant to achieve uniform character encoding.

Related Article

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.