Learn Notes _ filter application case (solve the whole station character garbled)

Source: Internet
Author: User

Solve all-station character garbled (post and get Chinese encoding problem)

Servlet:

L POST:request.setCharacterEncoding ("Utf-8");

L GET:

    • String username = request.getparameter ("username");
    • Username = new String (username.getbytes ("iso-8859-1"), "Utf-8");
1 Description garbled problem:

L GET the garbled problem in the request parameter;

    • Post request: request.setcharacterencoding ("Utf-8");
    • GET Request: New String (Request.getparameter ("xxx"). GetBytes ("Iso-8859-1"), "Utf-8");

L Response garbled problem: Response.setcontexttype ("Text/html;charset=utf-8").

Basically in each servlet to deal with garbled problem, so should put this work in the filter to complete.

2 Analysis In fact, the difficulty of the whole station garbled problem is to deal with the problem of Get request parameters.

If you just deal with the encoding of the POST request , and the response encoding problem, then this filter is too! Too! Too simple.

Public class Encodingfilter extends HTTPFilter {

Public void DoFilter (HttpServletRequest request,

HttpServletResponse response, Filterchain chain)

throws IOException, Servletexception {

String charset = this. Getinitparameter ("CharSet"); [Cui 1]

if (CharSet = = Null | | charset.isempty ()) {

CharSet = "UTF-8";

}[Cui 2]

Request.setcharacterencoding (CharSet); [Cui 3] //function calling request

Response. setContentType ("text/html;charset=" + charset); [Cui 4]

Chain.dofilter (request, response);

}

}

[Cui 1] Gets the initialization parameters in the configuration file: CharSet

[Cui 2] If the filter is not configured with the CharSet parameter, then the setting is encoded as UTF-8

[Cui 3] processing POST request encoding

[Cui 4] Handling Response Encoding

In the case of a POST request, when the target servlet is executed, when the Request.getparameter () method is called in the servlet, it is transcoded according to the encoding of the request.setcharacterencoding () setting! This means that calling the Request.setcharacterencoding () method in a filter affects the behavior of the Request.getparameter () method in the target servlet!

But if it is a GET request, how can we affect the behavior of the Request.getparameter () method? This is not good to do! It is not possible to call the Request.getparameter () method first to get the parameter, then manually transcode it and then apply it to the request! Because the request is only getparameter (), there is no Setparameter () method.

Processing GET request parameter encoding problem, need to release in filter, the Request object to "swap", that is, let the target servlet use our "swap" after the request object. This means that we need to ensure that all the methods in the request object after the "switch" are used as before "switched", and that the GetParameter () method has the ability to return the parameters after transcoding.

This may remind you of "inheritance", but it cannot be inherited, but "decorator mode (Decorator pattern)"!

Here are three ways to enhance the A object:

L Inheritance: The AA class inherits the type of a object: Class A, and then overrides the Fun1 () method, where the overridden Fun1 () method is the enhanced method. However, inheritance must know the true type of a object before it can be inherited. If we do not know the exact type of a object, but only know that the A object is an implementation class object of the IA interface, then you cannot use inheritance to enhance the A object;

L Decorator mode: AA class to implement the same interface as the A object: IA interface, also need to pass the A object to the AA class, and then all the method implementations in the AA class are done by the same method as the proxy a object, only the Fun1 () method adds some content before and after the same method as the proxy a object. This is the enhancement of the FUN1 () method;

Dynamic Agent: Dynamic agent is similar to decorator mode and is done by reflection. Dynamic agents will be on the last day of the basic strengthening of the explanation, here is no more nonsense.

The conditions for the request object to be enhanced, just in accordance with the characteristics of the decorator mode! Because we don't know the exact type of the request object, we know that request is an implementation class for the HttpServletRequest interface. This means that we write a class encodingrequest, to implement the HttpServletRequest interface, and then pass the original request to the Encodingrequest class! The implementation of all the methods in the HttpServletRequest interface in Encodingrequest is done by the proxy original request object, and only the GetParameter () method is added with the enhanced code!

Java EE has provided us with a Httpservletrequestwrapper class, which is the HttpServletRequest wrapper class, but it does any enhancement! You might say, write a decorative class, but do not enhance it, what is the purpose of it? What is the difference between using the object of this adornment class and using the original request?

Although the Httpservletrequestwrapper class is a httpservletrequest decoration class, it is not used for direct use, but for us to inherit! When we want to write a decoration class, but also to all do not need to enhance the method of implementation is very upset, but if you go to inherit the Httpservletrequestwrapper class, then you just need to rewrite the need to enhance the method.

3 Code

Encodingrequest

Public class Encodingrequest extends httpservletrequestwrapper [Cui 5] {

Private String CharSet;

Public Encodingrequest[Cui 6] (httpservletrequest request, String CharSet) {

Super (request);

this. CharSet = CharSet;

}

Public String GetParameter[Cui 7] (string name) {

HttpServletRequest request [cui 8] = (httpservletrequest) getrequest ();

String method = Request.getmethod ()[Cui 9] ;

if (Method.equalsignorecase ("Post[Cui] ")) {

Try {

Request.setcharacterencoding (CharSet); [Cui One]

} catch (Unsupportedencodingexception e) {}

} Else if(Method.equalsignorecase ("Get[Cui] ")) {

String value = request.getparameter (name); [Cui]

Try {

Value = new String (name.getbytes ("Iso-8859-1"), CharSet); [Cui]

} catch (Unsupportedencodingexception e) {

}

return value[Cui] ;

}

return request.getparameter (name);

}

}

Encodingfilter

Public class Encodingfilter extends httpfilter {

Public void DoFilter (httpservletrequest request,

HttpServletResponse response, Filterchain chain)

throws IOException, Servletexception {

String charset = this. Getinitparameter ("CharSet"); [Cui]

if (CharSet = = Null | | charset.isempty ()) {

CharSet = "UTF-8";

}[Cui]

Response.setcharacterencoding (CharSet);

Response.setcontenttype ("text/html;charset=" + charset);

Encodingrequest res = new encodingrequest (Request, CharSet); [Cui]

Chain.dofilter (res, response); [Cui]

}

}

Xml

  <filter>

    <filter-name>encodingfilter</filter-name>

    <filter-class>cn.itcast.filter.encodingfilter</filter-class>

    <init-param>

        <param-name>charset</param-name>

        <param-value>utf-8</param-value>

    </init-param>

  </filter>

  <filter-mapping>

    <filter-name>encodingfilter</filter-name>

    <url-pattern>/*</url-pattern>

  </filter-mapping>

[Cui 5] contains Httpservletrequst

[Cui 6] when creating this type of object, you need to provide the underlying request, as well as the character set

[Cui 7] overriding the GetParameter () method

[cui 8] convert the underlying object to HttpServletRequest

[Cui 9] Get Request method

[Cui] if it is a POST request

[Cui] set the code, ok!

[Cui] if it is a GET request

[Cui] get parameters from the underlying object

[Cui] transcode the parameters

[Cui] returns the value of the parameter after transcoding

[Cui] get initialization parameters

[Cui] if no initialization parameters are configured, set the CharSet to Utf-8

Create a Encodingrequest object using request as the underlying object

[Cui] release! Then the user gets the request is the Encodingrequest Object!

Learn Notes _ filter application case (solve the whole station character garbled)

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.