tomcat编解码过程

在使用tomcat的时候, 一直很好奇他是怎么对请求的参数进行编解码的,带着下面三个问题,一起看下。

1. get/post请求如何编解码,根据什么参数配置

2. URI编码

3.  中文参数为什么会出现乱码

1. 下图是tomcat各版本默认的编解码方式 

 

我们发现tomca6和tomcat7对URI的默认解码方式为ISO-8859-1, 但是涉及中文入参的请求,一般参数采用utf-8或gbk编码,这样就会出现编解码方式不一致,导致乱码。

tomcat编解码过程 

tomcat编解码过程

 tomcat编解码过程

2. URI编码

tomcat编解码过程

 上图解释了为什么我们会看到的浏览器地址栏的带有百分号的url地址,因为我们明明可能输入的是带中文的参数,但是看到的却是包含%的参数

3. 编解码过程的实现(以tomcat8为例)

Tomcat对于参数的处理方法为org.apache.catalina.connector.Request#parseParameters

Charset charset = getCharset();

boolean useBodyEncodingForURI = connector.getUseBodyEncodingForURI();
parameters.setCharset(charset);
// POST请求处理
if (useBodyEncodingForURI) {
    parameters.setQueryStringCharset(charset);
}
// GET请求,处理URI
parameters.handleQueryParameters();
org.apache.tomcat.util.http.Parameters 
private Charset queryStringCharset = StandardCharsets.UTF_8;
// GET请求处理,默认采用UTF-8编码
processParameters(decodedQuery, queryStringCharset);
POST请求从Content-type中取编码方式
Charset charset = getCharset();
public Charset getCharset() throws UnsupportedEncodingException {
    if (charset == null) {
        getCharacterEncoding();
        if (characterEncoding != null) {
            charset = B2CConverter.getCharset(characterEncoding);
        }
    }

    return charset;
}
public String getCharacterEncoding() {
    if (characterEncoding == null) {
        characterEncoding = getCharsetFromContentType(getContentType());
    }

    return characterEncoding;
}

从http头部获取响应值编码方式

public MessageBytes contentType() {
    if (contentTypeMB == null) {
        contentTypeMB = headers.getValue("content-type");
    }
    return contentTypeMB;
}