HTTP response and requested encoding problem __ code

Source: Internet
Author: User

the encoding in the 1.HttpServletRequest request is consistent

Using HTML form <form> submitting data to the server, obtaining parameter values through Request.getparameter (key) in the servlet, because the default character encoding for HTTP requests is iso-8859-1, A character encoding conversion is required after the parameter value is obtained. e.g.

HTML form:

<form action= "/testpro/servlet/checkservlet" >

Input: <input type= "text" name= "name"/>

<input type= "Submit"/>

</form>

Checkservlet:

String name = Request.getparameter ("name");

String Name_u = new String (Name.getbytes ("iso-8859-1"), "Utf-8");

"Note" here is the encoding format that is converted to Utf-8 because the <form> form's encoded format is utf-8. In the

<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">

Of course, the charset can also be designated as GB2312, at the same time in the request to obtain parameters, after the conversion of the encoding format is also GB2312, otherwise there will be garbled.

encoding in the 2.HttpServletResponse response

There are two ways to respond to Brower, one is OutputStream byte HttpServletResponse, and two are printwriter character streams.

2.1 OutputStream Byte stream (Byte stream encoding format is consistent with ContentType encoding format)

Response.getoutputstream (). Write ("unrestrained". GetBytes ("Utf-8"));

Response.setcontenttype ("Text/html;charset=utf-8");

You can also use the following two different ways

Response.setheader ("Content-type", "text/html;charset=utf-8");

Or

Response.setcontenttype ("text/html");

Response.setcharacterencoding ("Utf-8");

2.2 PrintWriter character stream (just specify the encoding format for contenttype)

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

PrintWriter out = Response.getwriter ();

Out.println ("unrestrained");

Out.write ("unrestrained"); Two ways of outputting the same effect

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.