We send requests to the server mainly in two forms: URLs, forms. and forms generally do not appear garbled problem, garbled problem is mainly in the URL above. With the introduction of the previous blogs we know that the URL to send the request encoding process to the server is really confusing. Different operating systems, different browsers, different Web character sets, will result in completely different encoding results. Is it too scary for programmers to take every result into account? Is there a way to ensure that the client makes a request to the server using only one encoding method?
Yes! Here I mainly provide the following several methods
First, JavaScript
Use JavaScript to encode the opportunity to not interfere with the browser, encode and then send the request to the server, and then decode the server. In mastering this approach, we need three ways to encode javascript: Escape (), encodeURI (), encodeURIComponent ().
Escape
Encodes the specified string using the Sio Latin character set. All non-ASCII characters are encoded as strings in the%xx format, where xx represents the 16-digit number that the character corresponds to in the character set. For example, the format corresponds to a code of%20. It corresponds to a decoding method of unescape ().
In fact, escape () cannot be used directly for URL encoding, and its true function is to return a Unicode encoded value of a character. For example, the above "I am cm" results for%U6211%U662FCM, where "I" corresponds to the code of 6211, "is" the encoding of 662F, "cm" code for CM.
Note that escape () does not encode "+". But we know that when we submit a form, the page will be converted to a + character if there are any spaces. When the server processes the data, the + number is processed into a space. So be careful when you use it.
encodeURI
The entire URL is encoded with the UTF-8 format output encoded string. But encodeURI does not encode any special characters except ASCII encoding such as:! @ # $& * () =:/;? + '.
encodeURIComponent ()
Converts the URI string into an escape format using the UTF-8 encoding format. More powerful than encodeuri,encodeuricomponent, it will be for those symbols that are not encoded in encodeURI (; / ? : @ & = + $, #) will all be encoded. However, encodeuricomponent only encodes the part of the URL individually, not the entire URL. Corresponding decoding function method decodeuricomponent.
Of course, we usually use the encodeURI side to encode the operation. The so-called JavaScript two-time code behind the two-time decoding is the use of this method. JavaScript solves this problem with one-time transcoding, two transcoding two solutions.
One-time transcoding
JavaScript transcoding:
var url = ' <s:property value= ' Webpath "/>/showmoblieqrcode.servlet?name= I am cm '; window.location.href = encodeURI ( URL);
URL:HTTP://127.0.0.1:8080/PERBANK/SHOWMOBLIEQRCODE.SERVLET?NAME=%E6%88%91%E6%98%AFCM after transcoding
Background processing:
String name = Request.getparameter ("name"); System.out.println ("Foreground incoming parameter:" + name); Name = new String (name.getbytes ("iso-8859-1"), "UTF-8"); System.out.println ("After decoding parameters:" + name);
Output Result:
Foreground incoming parameters:?????? Cm
After decoding the parameters: I am cm
Two times transcoding
Javascript
var url = ' <s:property value= ' Webpath "/>/showmoblieqrcode.servlet?name= I am cm '; window.location.href = encodeURI ( encodeURI (URL));
URL:HTTP://127.0.0.1:8080/PERBANK/SHOWMOBLIEQRCODE.SERVLET?NAME=%25E6%2588%2591%25E6%2598%25AFCM after transcoding
Background processing:
String name = Request.getparameter ("name"); System.out.println ("Foreground incoming parameter:" + name); Name = Urldecoder.decode (name, "UTF-8"); System.out.println ("After decoding parameters:" + name);
Output Result:
Foreground incoming parameters: E68891E698AFCM
After decoding the parameters: I am cm
Filter
Using filters, the filter LZ provides two kinds, the first set encoding, the second one directly in the filter decoding operation.
Filter 1
The filter is set directly in the encoding format of the request.
public class Characterencoding implements Filter { private filterconfig config; String encoding = NULL; public void Destroy () { config = null; } public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, servletexception { request.setcharacterencoding (encoding); Chain.dofilter (request, response); } public void init (Filterconfig config) throws servletexception { this.config = config; Gets the configuration parameter String str = config.getinitparameter ("encoding"); if (str!=null) { encoding = str; }} }
Configuration:
<!--Chinese filter configuration- <filter> <filter-name>chineseEncoding</filter-name> < filter-class>com.test.filter.characterencoding</filter-class> <init-param> < param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param > </filter> <filter-mapping> <filter-name>chineseEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Filter 2
The filter will decode the parameters directly in the processing method, and then reset the decoded parameters to the attribute of the request.
public class Characterencoding implements Filter {protected Filterconfig filterconfig; String encoding = NULL; public void Destroy () {this.filterconfig = null; }/** * Initialize * * * public void init (Filterconfig filterconfig) {this.filterconfig = Filterconfig; }/** * Convert INSTR to UTF-8 encoded form * * @param inStr Input String * @return UTF-8 encoded form of String * @throws Unsupp Ortedencodingexception */private string Toutf (String inStr) throws Unsupportedencodingexception {string ou Tstr = ""; if (inStr! = null) {outstr = new String (instr.getbytes ("iso-8859-1"), "UTF-8"); } return outstr; }/** * Chinese garbled filter processing */public void DoFilter (ServletRequest servletrequest, Servletresponse servletre Sponse, Filterchain chain) throws IOException, servletexception {httpservletrequest request = (Httpserv Letrequest) ServletRequest; HttpServletResponse response = (httpservletresponse) servletresponse; How to obtain a request (1.post or 2.get), different processing according to different request method String method = Request.getmethod (); 1. A request that is submitted as a post is directly encoded as UTF-8 if (Method.equalsignorecase ("POST")) {try {Request.setch Aracterencoding ("UTF-8"); } catch (Unsupportedencodingexception e) {e.printstacktrace (); }}//2. Request submitted as Get-else {//Take out the client-submitted parameter set enumeration<string> Paramnames = Request.getparamete Rnames (); Iterate over the parameter set to remove the name and value of each argument while (Paramnames.hasmoreelements ()) {String name = Paramnames.nextelement ( ); Take out the parameter name String values[] = request.getparametervalues (name); Take its value according to the parameter name//if the parameter value set is NOT NULL if (values! = NULL) {//traversal parameter value set for (int i = 0; i < values.length; i++) {try {//The loop loops each value call Toutf (Values[i]) method to convert the character encoding of the parameter value String vlustr = Toutf (Values[i]); Values[i] = vlustr; } catch (Unsupportedencodingexception e) {e.printstacktrace (); }}//To hide the value in the form of a property in Request Request.setattribute (name, values); }}}//Set the response mode and support Chinese character set Response.setcontenttype ("Text/html;charset=utf-8"); Proceed to the next filter, and no next filter executes the request Chain.dofilter (requests, response); }}
Configuration:
<!--Chinese filter configuration- <filter> <filter-name>chineseEncoding</filter-name> < filter-class>com.test.filter.characterencoding</filter-class> </filter> < filter-mapping> <filter-name>chineseEncoding</filter-name> <url-pattern>/*</ Url-pattern> </filter-mapping>
Other
1, set pageencoding, ContentType
<%@ page language= "java" contenttype= "Text/html;charset=utf-8" pageencoding= "UTF-8"%>
2. Set Tomcat's uriencoding
By default, the Tomcat server is encoded using the ISO-8859-1 encoded format, and the uriencoding parameter encodes the URL of the GET request, so we only need the <connector of the Server.xml file in Tomcat Add uriencoding= "Utf-8" to the > tag.
Java Chinese garbled solution (eight)-----solve the URL Chinese garbled problem