Chinese garbled problem in Java Web--Chinese garbled between browser and server

Source: Internet
Author: User

I. Garbled cause

When the browser sends a request to the server, it encodes the requested parameters (UTF-8 format), which is decoded when the server receives the request parameters, and is garbled due to the different format of the browser and the server encoding. Different server default encoding format, tomcat default iso-8859-1.

Two. Get, POST request garbled solution--Simple version1. Get request

Get requests are available in three different solutions.

A. Through the first encoding and then decoding mode. When the server is decoded in a different encoding format, it can be garbled by first encoding the string into the original byte stream in the same encoding format as the server, and then decoding the string class to generate the correct strings. The code is as follows:

String Newjoo = new String (Joo.getbytes ("iso-8859-1"), "UTF-8"); Joo to String

B. Modify the Tomcat server configuration file and set the URL encoding format. Server.xml configuration file in the Conf folder under the Tomcat installation directory, in <connector connectiontimeout= "20000" port= "8090" protocol= "http/1.1" redirectport= add uriencoding= "UTF-8" property in "8443"/>. This method has no effect on post garbled because it can only set the request parameters that are carried in the URL, and the POST request parameters are stored in the request body.

C. In the page with the JS function such as: encoding (), encoding, the background with Java code decoding. This method of trouble, not much to say.

Three methods each have their own shortcomings, the use of a method needs to add that code in each servlet class, resulting in code redundancy, poor maintainability, using the B method can be achieved once and for all, but what if there are other items in the server that require different URL encoding format? So this is not flexible, unfriendly, and the post request garbled invalid; C method defect with a method.

2. Post request

Post request garbled resolution is simple and requires only one line of code. There is a method in the request object that sets the encoding format:

Request.setcharacterencoding ("Utf-8")

Similarly, this approach is flawed. First, it causes code redundancy, which makes maintainability worse, and secondly, it only works on the parameters in the request body, and the GET request is garbled and invalid.

Three. Post get garbled solution version--filter1. How to Do

There are three ways to get request parameters in a servlet: GetParameter (), Getparametervalues (), Getparametermap (), GetParameter () returns a string type for obtaining a single request parameter , Getparametervalues () returns the string[] type and is used to get a single request parameter, except that the request parameter contains multiple values, such as a check box, Getparametermap () return value of Map<string, string[] To get all the request parameters.

The ServletRequest interface defines these three methods, Tomcat implements these three methods, but the implementation of the source code does not do coding-related processing, if we define a class to implement the ServletRequest interface and then rewrite the three methods, And in which the post and get garbled can not only solve the problem once and for all, avoid code redundancy, but also ensure the flexibility to ensure that the same server on the other projects. But the implementation of the ServletRequest interface must implement all of these methods, too much work!

Sun has long considered this problem, very thoughtful design of a wrapper class to implement the ServletRequest interface, we only need to define a class to inherit the Httpservletrequestwrapper class, and rewrite three methods to achieve the purpose. Let's take a look at the inheritance relationship of the Httpservletrequestwrapper class:

public class Httpservletrequestwrapper extends Servletrequestwrapper implements HttpServletRequest You can see that it inherits the Servletrequestwrapper class, and the Servletrequestwrapper class implements the HttpServletRequest interface. The HttpServletRequest interface is a sub-interface of the ServletRequest interface, so Httpservletrequestwrapper implements all the methods of the ServletRequest interface.

Our goal is to have all servlets use the overridden method, which we've solved to rewrite the three methods to get the request parameters, but there is one more question-how can all Servlets use the method we override, that is, where to rewrite the three methods. To solve this problem, the first thing to understand is the life cycle of the servlet, and here's a simple introduction, where Tomcat instantiates the Servlet object and executes the init () method in the initialization operation. When Tomcat receives the request, it creates the HttpServletRequest and HttpServletResponse objects, then executes the service () method in the Servlet object to determine how the request is requested and calls Doget () or Dopost () method, where two objects are passed as arguments to the doget () and Dopost () methods, and the Destory () method in the Servlet class is executed when Tomcat stops normally. Knowing the life cycle of the servlet we know that if we want all the servlet classes to use the overridden method, we can modify Tomcat's source code, Making it a custom object created in the process of creating httpservletrequest and HttpServletResponse objects, but this is a lot of work, and it also affects other projects, inflexible and unfriendly. To the Java Web one of the three main components of the filter surfaced.

filter--filters, which can be executed before all servlets, we define class inheritance Httpservletrequestwrapper in a custom filter, rewrite the three fetch request parameter method, and pass it to the servlet for our purposes.

2. Code implementation

Web. XML configuration

<filter> <filter-name>encodingFilter</filter-name> <filter-class>   Ff.charset.encodingfilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> < Filter-name>encodingfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping >

Custom Filter Class

public class encodingfilter implements filter{  private string  encoding;  //  encoding Format    @Override  public void init (filterconfig  Filterconfig)  throws ServletException {    //  get the encoding format from Web. XML    this.encoding = filterconfig.getinitparameter ("encoding"); }  @Override  public  void dofilter (Servletrequest request, servletresponse response, filterchain  chain)    throws ioexception, servletexception {    //   Down transformation into httpservletrequest  httpservletrequest req =  (HttpServletRequest)   request;  httpservletresponse res =  (HttpServletResponse)  response;     //  set the data Response encoding format   response.setcontenttype ("text/html;charset="  + encoding);     //  Creating decoration Classes  myhttprequest myhr = new myhttprequest (req, encoding);     //  release   chain.dofilter (myhr, res); }  @Override  public void  Destroy ()  {  // todo auto-generated method stub   }}

Custom class Inheritance Httpservletrequestwrapper

The above mentioned Getparametermap () is used to get all the request parameters, it can also get a single request parameter, all we just need to override this method, and then the other two methods call this method can be.

public class myhttprequest extends httpservletrequestwrapper { private  httpservletrequest req;  //  Original Request Object  private string encoding;  //   Encoding Formats  private boolean flag = true;  //  switches  public  Myhttprequest (httpservletrequest request, string encoding)  {  super (request);   this.req = request;  this.encoding = encoding; }  @ Override public string getparameter (String name)  {  Map<String,  String[]> map = getparametermap ();   string[] values = map.get (name) ;  if  (null == values)  {   return null;  }   return values[0]; }  @Override  public string[] getparametervalues (String  name) &NBSP;{&NBSP;&NBSP;MAP&LT String, string[]> map = getparametermap ();   return map.get (name);  }   @Override  public map<string, string[]> getparametermap ()  {   String method = req.getmethod ();  if  (Method.equalsignorecase ("POST"))  {       try {    req.setcharacterencoding (encoding);     return req.getparametermap ();   } catch  ( unsupportedencodingexception e)  {    e.printstacktrace ();    }   } else if  (Method.equalsignorecase ("get")  && true ==  Flag)  {      //  through flag to make this code once the request is executed only once, because the execution is equivalent to decoding and re-encoding multiple times, resulting in garbled     map<string, string[]> map = req.getparametermap ();  //  An object is assigned an address, a map points to an Req address, and modifying the map value is equivalent to modifying a property value in req  &nBsp; set<string> set = map.keyset ();   //  iterates through all the values in the map, Solve get garbled    iterator<string> iterator = set.iterator ();   by decoding and recoding  while  (Iterator.hasnext ())  {    string[] values = map.get ( Iterator.next ());    if  (null != values)  {      for  (int i = 0; i < values.length; i++)  {       try {       values[i] = new  String (Values[i].getbytes ("Iso-8859-1"),  encoding);              } catch  (unsupportedencodingexception e)  {        e.printstacktrace ();       }     }          }   }      flag = false;    return map;  }     //  other requests execute the original get parameter method, except get  There are other request methods outside post   return super.getparametermap ();  }}


Chinese garbled problem in Java Web--Chinese garbled between browser and server

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.