Java Web project all kinds of garbled solution __web

Source: Internet
Author: User
Tags goto java web tomcat server
Original works, allow reprint, reprint, please be sure to hyperlink form to indicate the original source of the article, the author's information and I declare. Otherwise, legal liability will be held.
Author: Eternal の_☆ Address: http://blog.csdn.net/chenghui0317/article/details/10299103 First, the preface

The current Web project, a lot of garbled situation has not been unified solution, more or less affect the development efficiency and extend the development time, so summed up on the Java Web project a variety of garbled solutions.


second, prepare the condition 1, a common Web project webproject;

2, a Web server Tomcat.


third, the analysis of various garbled situation

1, the coding format of the project and the page file encoding format is not the same as whether there is a conflict.

A: WebProject Project encoding format is "GBK", the project under the page encoding format is "UTF-8", the practice found that the project coding format and page coding format will not have any problems, the display of Chinese is not garbled.

To view the encoding format of an item, the specific value displayed in the project --> right-->properties--> Text file encoding box is the project encoding format.

The encoding format for viewing the paging file can be displayed in the page --> right-->properties--> Text file encoding box, which is the encoding format of the paging file.


2, the page's File encoding format and page content encoding format is not the same whether there is a conflict.

Answer:<1> the page file encoding format to "UTF-8", the content of the page in the encoding format changed to "GBK", specifically as follows:

<%@ page language= "java" contenttype= "text/html; CHARSET=GBK "pageencoding=" GBK "%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
Results found garbled, the specific effect is as follows:


So the page's file encoding format must be the same as the page content encoding format, otherwise the display is definitely garbled.

<2> In addition, if the format of the page in the Eclipse display is good, this time to change the file encoding format will be garbled, if you want to change the file encoding format, you can do this: first will display the correct content to copy and then modify the file encoding format, this time the file is displayed in garbled, You can then cover the copied content directly on this page.


<3> if the above code to the pageencoding to "UTF-8" found that the display is normal, so it can be said that the page display is garbled and charset specified value independent.


<4> But if the above code pageencoding= "UTF-8" This attribute directly removed, and then show the effect, found garbled. If the value of the ContentType attribute is changed to contenttype= "text/html;" Charset=utf-8 "trial effect, specific as follows:


So you can understand that when you do not specify the pageencoding attribute, the CharSet will be ignored, and if you do not specify the pageencoding attribute, the page will display the specific effect according to the CharSet encoded value.


<5> if the value specified by CharSet is GBK, this time because there is no pageencoding, so the page content is displayed according to GBK encoding, but does not conform to the file encoding format, the index causes garbled. The specific effect is as follows:

<6> now there is another situation, if the pageencoding specified UTF-8, but charset specified is GBK, GB2312 this time the page display will not garbled.


<7> But if the charset specified is iso-8859-1, this time the page display is garbled, the specific effect is as follows:


<8> But if the charset specified is Big5, this is the page display is only partially garbled, the specific effect is as follows:

So BIG5 will only be sensitive to traditional or no traditional format text.


<9> now try again, the contenttype sign is also removed, specify the Charset=utf-8 in the content attribute in the META tag, the effect is as follows:

A different format of the garbled display ...


To sum up: in the JSP if you want to display the correct content, and ensure that it is not garbled, you must specify the contenttype or Pageencoding attributes and file encoding format consistent. And if they all exist, then pageencoding must be in line with the file encoding format, contenttype must be in the Chinese encoding format.


3, through the URL to pass the Chinese parameter when received garbled how to solve.

Answer:<1> Create a new servlet named Encodeservlet, add a hyperlink in encode.jsp to pass a parameter to jump to the Serlvet.

Hyperlinks are as follows:

<a href= "servlet/encodeservlet?param= Chinese" >go to servlet</a>

The servlet receives the parameters, and the specific get methods are handled as follows:

/**
* @see httpservlet#doget (httpservletrequest request, httpservletresponse response) * * *
Protec        Ted void Doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
String param = request.getparameter ("param");
Request.getrequestdispatcher ("..    /encode.jsp?param= "+param). Forward (request, response);
}
After debugging found that the parameters are garbled:


<2> this is because the parameter is passed through the URL by the HTTP Hypertext protocol, its format is iso-8859-1, so you can set the Tomcat Server global URL request format, all requests will follow this encoding format passed parameters. Specifically as follows:

In the conf/server.xml of the Tomcat installation directory, locate the connector for the property configuration of Protocol= "http/1.1" and add the uriencoding attribute inside, as follows:

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

Uriencoding, as the name suggests, is only for requests that are delivered by URLs, that is, get requests.


<3> and if you do so, you can no longer use param = new String (param.getbytes ("iso-8859-1"), "UTF-8"), and turn the code so that it becomes garbled.


<4> Alternatively, you can reassign the encoding after you receive the parameter, as follows:

		String param = request.getparameter ("param");
		param = new String (param.getbytes ("iso-8859-1"), "UTF-8");

Debug page, found not successful, the specific effect is as follows:

No effect,,, why,. Because the content of the page encoding is UTF-8, but the URL when it is passed can only pass iso-8859-1 encoding, if the direct transmission of UTF-8 encoded content, then regardless of the background how the conversion has no effect. It does not help to reassign charset even in the servlet.


<5> But if you type directly in the Address bar: http://localhost:8080/webProject/servlet/encodeServlet?param= Chinese

and modify some of the code, specific changes as follows:

        Response.setcontenttype ("Text/html;charset=utf-8");
        String param = request.getparameter ("param");
        param = new String (param.getbytes ("iso-8859-1"), "UTF-8");

Then the effect is as follows:


This is no problem.


<6> But what if you do not want to use the new String () recoding to receive Chinese? , you can modify the source code, specific as follows:

		Request.setcharacterencoding ("UTF-8");
		String param = request.getparameter ("param");
		param = new String (param.getbytes ("iso-8859-1"), "UTF-8");
		
The character encoding format can be set, the specific effect is as follows:



Practice has shown that whether the hyperlink jumps to the servlet or directly in the URL input Chinese jump to the servlet to use only request.setcharacterencoding ("UTF-8"); The Unified coding format enables you to receive the correct parameters.

In the beginning always thought Request.setcharacterencoding ("UTF-8"); You can only handle the parameters of a POST request, as well as a GET request.


<7> since it is so effective, you can use a filter to uniformly process any requested encoding format in order to avoid duplicate use of this line of code or forget to use it to cause garbled characters. Once.

The specific filter code is as follows:

Package com.struts2.util;

Import java.io.IOException;
Import Javax.servlet.Filter;
Import Javax.servlet.FilterChain;
Import Javax.servlet.FilterConfig;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletRequest;

Import Javax.servlet.ServletResponse;

Import Org.apache.log4j.Logger;
	public class Characterfilter implements Filter {private Logger Logger = Logger.getlogger (This.getclass ());
	String encoding = NULL; @Override public void Destroy () {Logger.info (***************the Characterfilter class ' Destroy () is invoking. *******
	********"); @Override public void Dofilter (ServletRequest request, servletresponse response, Filterchain Filterchain) throws I
		Oexception, Servletexception {request.setcharacterencoding (encoding);
		response.setcharacterencoding (encoding);
	Filterchain.dofilter (request, response); @Override public void init (Filterconfig filterconfig) throws Servletexception {Logger.info ("***************the Cha Racterfilter class ' iniT () is invoking. *************** ");
	encoding = Filterconfig.getinitparameter ("encoding");
 }

}

The Web.xml is then configured as follows:

  <filter>
    <filter-name>characterFitler</filter-name>
    <filter-class> com.struts2.util.characterfilter</filter-class>
    <init-param>
      <param-name>encoding </param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter >
  <filter-mapping>
    <filter-name>characterFitler</filter-name>
    < Url-pattern>/*</url-pattern>
  </filter-mapping>

<8> however, in actual development, the above configuration can sometimes specify the encoding success when processing get requests, sometimes the encoding fails, the success rate is probably 60-70% between, still do not know why so ...

Solution:

Use the JS function code, and then the background to decode, the specific foreground code is as follows:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
The background decoding code is as follows:

		Request.setcharacterencoding ("UTF-8");
		Response.setcontenttype ("Text/html;charset=utf-8");
		String param = request.getparameter ("param");
		param = new String (param.getbytes ("iso-8859-1"), "UTF-8")//the encoding used to process the conversion GET request directly
		//param = Urlencoder.encode ( param);//This is a method for encoding
		param = urldecoder.decode (param);//This is a method for decoding

OK, this way to solve the JS function request background garbled situation.


<9> In addition to the use of printwriter output when the garbled, the specific code is as follows:

		PrintWriter out = Response.getwriter ();
		Out.print ("Received parameters are:" +param);
		
		Out.close ();
The specific effect is as follows:


Here you can add Response.setcontenttype ("Text/html;charset=utf-8") to the top of the servlet request; Set the content encoding format to output the correct effect, as shown in the following figure:


Sum up:

(1) When the parameters appear garbled, if the GET request can be unified set Tomcat encoding processing format, so that all the URLs sent requests are sent in the specified format.

(2) request.setcharacterencoding ("UTF-8"), the main user get/post request set the entire servlet encoding format, the advantage is to prevent the transfer of Chinese parameters garbled.

(3) Response.setcontenttype ("Text/html;charset=utf-8"); Mainly used to specify the content format of the current request, the advantage is to prevent the output content when the Chinese garbled.

(4) If the processing of Chinese garbled in the above methods can not be resolved, it is necessary to use the JS before the code two times, the background decoding the way to deal with.


4, whether there are other framework configuration directly solve the Chinese garbled situation.

<1> if Struts2 is used in the project, you can configure a constant in Sturts.xml to specify the encoding of all post requests, as follows:

	<constant name= "struts.i18n.encoding" value= "UTF-8" ></constant>


<2> if spring is used in a project, configuring a filter in Web.xml can also solve the problem of coded garbled, as follows:

  <filter>
    <filter-name>encodingFilter</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>
  <filter-mapping>
    < filter-name>encodingfilter</filter-name>
    <url-pattern>/*</url-pattern>
  </ Filter-mapping>










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.