Solve Chinese garbled characters in URL parameters passed by get Method

Source: Internet
Author: User

From: http://www.javaeye.com/topic/483158

Application 1: solves the problem of Chinese garbled characters in Tomcat (a simple one first)

In tomcat, we usually solve the Chinese Garbled text problem as follows:

Filter code:

Java code
  1. Package filter;
  2. Import java. Io .*;
  3. Import javax. servlet .*;
  4. Import javax. servlet. http .*;
  5. Import wrapper. gethttpservletrequestwrapper;
  6. Public class contenttypefilter implements filter {
  7. Private string charset = "UTF-8 ";
  8. Private filterconfig config;
  9. Public void destroy (){
  10. System. Out. println (config. getfiltername () + "destroyed ");
  11. Charset = NULL;
  12. Config = NULL;
  13. }
  14. Public void dofilter (servletrequest request, servletresponse response,
  15. Filterchain chain) throws ioexception, servletexception {
  16. // Set the character encoding of the Request Response
  17. Request. setcharacterencoding (charset );
  18. Response. setcharacterencoding (charset );
  19. Httpservletrequest Req = (httpservletrequest) request;
  20. System. Out. println ("---- the request is" + config. getfiltername () + "filtered ");
  21. // Execute the next filter (if any, otherwise execute the target servlet)
  22. Chain. dofilter (req, response );
  23. System. Out. println ("---- the response is" + config. getfiltername () + "filtered ");
  24. }
  25. Public void Init (filterconfig config) throws servletexception {
  26. This. Config = config;
  27. String charset = config. getservletcontext (). getinitparameter ("charset ");
  28. If (charset! = NULL & charset. Trim (). Length ()! = 0)
  29. {
  30. This. charset = charset;
  31. }
  32. }
  33. }

 

Filter configuration in Web. xml:

XML Code
  1. <! -- Configure the character encoding to the application initialization parameter instead of the private initialization parameter of the filter because JSP and other places may also need to use -->
  2. <Context-param>
  3. <Param-Name> charset </param-Name>
  4. <Param-value> UTF-8 </param-value>
  5. </Context-param>
  6. <Filter>
  7. <Filter-Name> contenttypefilter </filter-Name>
  8. <Filter-class> filter. contenttypefilter </filter-class>
  9. </Filter>
  10. <Filter-mapping>
  11. <Filter-Name> contenttypefilter </filter-Name>
  12. <URL-pattern>/* </url-pattern>
  13. </Filter-mapping>

Request. setcharacterencoding (charset); It must be written before request. getparameter () is used for the first time, so that the parameter can be obtained according to the character encoding that has been set.
Response. setcharacterencoding (charset); It must be written before printwriter out = request. getwriter (). In this way, the out can be output according to the configured character encoding.

Through the filter, we can ensure that the character encoding of the request and response is set before the servlet or JSP execution.

However, this does not completely solve the Chinese Garbled text problem:

For post requests, neither the "get parameter link" nor the "output link" is correct;

For GET requests, there is no problem with the "output stage", but the "get parameters stage" still shows Chinese garbled characters, so the garbled characters are directly output during output.

The reason is that the location of the parameters stored in the post and get requests is different:

Post parameters are stored in the message body of the request data packet. The get method parameters are stored in the URI field of the request line of the request packet? Start attaching it to the URI field in the form of param = Value & parame2 = value2. Request. setcharacterencoding (charset); only applies to the data in the message body and does not take effect for parameters in the URI field. We usually use the following code to complete encoding conversion:

Java code
  1. String paramvalue = request. getparameter ("paramname ");
  2. Paramvalue = new string (paramvalue. Trim (). getbytes ("ISO-8859-1"), charset );

But every time such a conversion is really troublesome, is there a unified solution?

Solution 1: Set the uriencoding attribute to the appropriate character encoding in the connector element of tomcat_home \ conf \ Server. xml.

Java code
  1. <Connector Port = "8080" protocol = "HTTP/1.1"
  2. Connectiontimeout = "20000"
  3. Redirectport = "8443"
  4. Uriencoding = "UTF-8"
  5. />

The disadvantage is that other applications under the same Tomcat will also be affected. It is also difficult to modify the configuration of classes during each deployment.

Solution 2: Custom request wrapper wraps the request and adds the character encoding conversion to the getparameter () method.

Java code
  1. Package wrapper;
  2. Import java. Io. unsupportedencodingexception;
  3. Import java.net. urldecoder;
  4. Import javax. servlet. http. httpservletrequest;
  5. Import javax. servlet. http. httpservletrequestwrapper;
  6. Public class gethttpservletrequestwrapper extends httpservletrequestwrapper {
  7. Private string charset = "UTF-8 ";
  8. Public gethttpservletrequestwrapper (httpservletrequest request ){
  9. Super (request );
  10. }
  11. /**
  12. * Get the reference and character encoding of the decorated object
  13. * @ Param request
  14. * @ Param charset
  15. */
  16. Public gethttpservletrequestwrapper (httpservletrequest request,
  17. String charset ){
  18. Super (request );
  19. This. charset = charset;
  20. }
  21. /**
  22. * In fact, it is to call the getparameter method of the encapsulated request object to obtain the parameter, and then encode and convert it.
  23. */
  24. Public String getparameter (string name ){
  25. String value = super. getparameter (name );
  26. Value = NULL? Null: Convert (value );
  27. Return value;
  28. }
  29. Public String convert (string target ){
  30. System. Out. println ("Before encoding conversion:" + target );
  31. Try {
  32. Return new string (target. Trim (). getbytes ("ISO-8859-1"), charset );
  33. } Catch (unsupportedencodingexception e ){
  34. Return target;
  35. }
  36. }
  37. }

The code for modifying the dofilter method of the filter is as follows:

Java code
  1. Public void dofilter (servletrequest request, servletresponse response,
  2. Filterchain chain) throws ioexception, servletexception {
  3. // Set the character encoding of the Request Response
  4. Request. setcharacterencoding (charset );
  5. Response. setcharacterencoding (charset );
  6. // Newly added code
  7. Httpservletrequest Req = (httpservletrequest) request;
  8. If (req. getmethod (). inclusignorecase ("get "))
  9. {
  10. Req = new gethttpservletrequestwrapper (req, charset );
  11. }
  12. System. Out. println ("---- the request is" + config. getfiltername () + "filtered ");
  13. // Reference of the actual package object passed to the target servlet or JSP, instead of the original httpservletrequest object
  14. Chain. dofilter (req, response );
  15. System. Out. println ("---- the response is" + config. getfiltername () + "filtered ");
  16. }

In this way, the getparameters method of the package is called in the servlet to obtain the parameter, and the character encoding conversion process has been completed. We do not need to convert the character encoding every time we obtain the parameter.

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.