[Tip]12. From the Spring coding filter

Source: Internet
Author: User
Tags urlencode

One of the students asked me a question, a sudden inspiration, he used the spring filter, the front desk using get method to send a request to the back end, because it contains Chinese data, the result is garbled at the back end, he asked me why? Clearly in spring is also equipped with a character filter, but there is garbled, so I looked at the spring implementation of the filter, The following is the implementation code of the filter Org.springframework.web.filter.CharacterEncodingFilter.java

 Public classCharacterencodingfilterextendsOnceperrequestfilter {PrivateString encoding; Private BooleanForceencoding =false; /*** Set the encoding to use for requests. This encoding'll is passed into a * {@linkjavax.servlet.http.httpservletrequest#setcharacterencoding} call.  * <p>whether This encoding would override existing request encodings * (and Whether It'll be applied as default Response encoding as well) * depends on the {@link#setForceEncoding "forceencoding"} flag. */     Public voidsetencoding (String encoding) { This. Encoding =encoding; }    /*** Set whether the configured {@link#setEncoding Encoding} of this filter * are supposed to override existing request and response encodings. * <p>default is "false", i.e. does not modify the encoding if * {@linkjavax.servlet.http.httpservletrequest#getcharacterencoding ()} * Returns a Non-null value. Switch this to ' true ' to enforce the specified * encoding in any case, applying it as Default response encoding as Wel     L. */     Public voidSetforceencoding (Booleanforceencoding) {         This. forceencoding =forceencoding; } @Overrideprotected voiddofilterinternal (httpservletrequest request, httpservletresponse response, Filterchain Filterchain) throwsservletexception, IOException {if( This. Encoding! =NULL&& ( This. forceencoding | | request.getcharacterencoding () = =NULL) { request.setcharacterencoding ( this.encoding); Setting here is the problem of encoding parameters for handling post            if( This. forceencoding) {response.setcharacterencoding ( This. Encoding);    }} filterchain.dofilter (request, response); }}

In Web. XML, this filter is configured as follows: The two parameters to be set are encoding, forceencoding, setting the character set individually and setting the character set, and the filter is very simple

    <Filter>        <Filter-name>Characterencodingfilter</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>

Sometimes, see the source to know some truth, all know spring just use request.setcharacterencoding (this.encoding), help us to deal with the post way garbled problem, encountered get method of submission, Or it will appear garbled.

Note : Since the beginning of the tomcat5.x, the get mode and the Post method of the submission of different processing methods [so in the two-stage learning should be strictly differentiated get and POST request processing, develop good habits, think about whether to do] . The Post method is to use Request.setcharacterencoding () to set the encoding, if not set, is to follow the default iso-8859-1 to encode ; Get mode commits always use the default iso-8859-1 to encode parameters .

Chinese garbled Solutions

1. Use of string[is also the most common way]

New // get to byte[] By default encoding, and then encode  UTF-8 again

2. Configure uriencoding= "UTF-8" in Server.xml in Tomcat

<uriencoding= "UTF-8"  port= "8080"  protocol= "http/1.1"                 connectiontimeout  = "20000"               redirectport  = "8443"  />

3. Encode passed parameters using JavaScript

Additional Reading

The

JS encoding differs in several ways:

1.window.escape () is the same as the Httputility.urlencodeunicode () encoding format: A Chinese character coding is%uxxxx format
Characters that are not encoded by Window.escape are: @ _-. */+  This is not in accordance with the interpretation on http://www.w3school.com.cn/js/jsref_escape.asp

 

2 .window.encodeuricomponent () [I recommend this way] is the same as Httputility.urlencode () encoding format: Chinese character coding a format of%xx%xx%xx

Characters that are not encoded by Window.encodeuricomponent are: '   ( )   * - . _  ! ~   this is in accordance with the http://www.w3school.com.cn/js/jsref_encodeURIComponent.asp interpretation

Characters that will not be httputility.urlencode encoded are: '   ( )   * -  .  _ ! In comparison, Httputility.urlencode is one ~ encoding

  than window.encodeuricomponent;

3. Characters that are not encoded by Window.encodeuri are:-   _  . !  * ( )  ; / ? :  @  &  =  $ , &nbs P #, in contrast to encodeURIComponent, found encodeURI wrong:/?:@&=+$, #这些用于分隔 the punctuation of the URI component

The first: The case demo illustrates the JavaScript code: Window.self.location= "searchbytext.action?searchtext=" +encodeURIComponent ( encodeURIComponent (Seartext)); Java Background processing code: SearchText=java.net.urldecoder.decode (SearchText, "UTF-8"); /* why to two times the reason: The background Java code to SearchText assignment, itself has used a decoding, but the decoding result is still wrong. So we can do two encoding on the page, so that the background automatically can be offset one time, and then use Searchtext=java.net.urldecoder.decode (SearchText, "UTF-8"), a decoding is good. "This way is still used more, I personally use less"* *

Personally, I prefer the first case, but sometimes the server has a compatibility problem, I have encountered in the use of Tomcat, placed in the WebLogic after the not good, then I only use the third way, for the third way I do not explain too much, I hope you have an impression

I wrote so many, why do you always do not reply to me, to introduce me to an Object! < ( ̄▽ ̄) > Wow haha ...!

[Tip]12. From the Spring coding filter

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.