003.GET和POST中文乱码问题解决专题

有一枚学生问问了我一个问题,突然灵感爆发,他使用的Spring的过滤器,前台利用GET方式向后端发出一个请求,由于里面含有中文数据,结果在后端显示的是乱码,他问我为什么?明明在Spring里面也配了字符过滤器,却出现了乱码,所以就看了一下spring实现的该过滤器,下面是过滤器的实现代码org.springframework.web.filter.CharacterEncodingFilter.java

/*
 * Copyright 2002-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.Assert;

/**
 * Servlet Filter that allows one to specify a character encoding for requests.
 * This is useful because current browsers typically do not set a character
 * encoding even if specified in the HTML page or form.
 *
 * <p>This filter can either apply its encoding if the request does not already
 * specify an encoding, or enforce this filter's encoding in any case
 * ("forceEncoding"="true"). In the latter case, the encoding will also be
 * applied as default response encoding (although this will usually be overridden
 * by a full content type set in the view).
 *
 * @author Juergen Hoeller
 * @since 15.03.2004
 * @see #setEncoding
 * @see #setForceEncoding
 * @see javax.servlet.http.HttpServletRequest#setCharacterEncoding
 * @see javax.servlet.http.HttpServletResponse#setCharacterEncoding
 */
public class CharacterEncodingFilter extends OncePerRequestFilter {

    private String encoding;

    private boolean forceRequestEncoding = false;

    private boolean forceResponseEncoding = false;


    /**
     * Create a default {@code CharacterEncodingFilter},
     * with the encoding to be set via {@link #setEncoding}.
     * @see #setEncoding
     */
    public CharacterEncodingFilter() {
    }

    /**
     * Create a {@code CharacterEncodingFilter} for the given encoding.
     * @param encoding the encoding to apply
     * @since 4.2.3
     * @see #setEncoding
     */
    public CharacterEncodingFilter(String encoding) {
        this(encoding, false);
    }

    /**
     * Create a {@code CharacterEncodingFilter} for the given encoding.
     * @param encoding the encoding to apply
     * @param forceEncoding whether the specified encoding is supposed to
     * override existing request and response encodings
     * @since 4.2.3
     * @see #setEncoding
     * @see #setForceEncoding
     */
    public CharacterEncodingFilter(String encoding, boolean forceEncoding) {
        this(encoding, forceEncoding, forceEncoding);
    }

    /**
     * Create a {@code CharacterEncodingFilter} for the given encoding.
     * @param encoding the encoding to apply
     * @param forceRequestEncoding whether the specified encoding is supposed to
     * override existing request encodings
     * @param forceResponseEncoding whether the specified encoding is supposed to
     * override existing response encodings
     * @since 4.3
     * @see #setEncoding
     * @see #setForceRequestEncoding(boolean)
     * @see #setForceResponseEncoding(boolean)
     */
    public CharacterEncodingFilter(String encoding, boolean forceRequestEncoding, boolean forceResponseEncoding) {
        Assert.hasLength(encoding, "Encoding must not be empty");
        this.encoding = encoding;
        this.forceRequestEncoding = forceRequestEncoding;
        this.forceResponseEncoding = forceResponseEncoding;
    }


    /**
     * Set the encoding to use for requests. This encoding will be passed into a
     * {@link javax.servlet.http.HttpServletRequest#setCharacterEncoding} call.
     * <p>Whether this encoding will override existing request encodings
     * (and whether it will be applied as default response encoding as well)
     * depends on the {@link #setForceEncoding "forceEncoding"} flag.
     */
    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    /**
     * Return the configured encoding for requests and/or responses
     * @since 4.3
     */
    public String getEncoding() {
        return this.encoding;
    }

    /**
     * Set whether the configured {@link #setEncoding encoding} of this filter
     * is supposed to override existing request and response encodings.
     * <p>Default is "false", i.e. do not modify the encoding if
     * {@link javax.servlet.http.HttpServletRequest#getCharacterEncoding()}
     * returns a non-null value. Switch this to "true" to enforce the specified
     * encoding in any case, applying it as default response encoding as well.
     * <p>This is the equivalent to setting both {@link #setForceRequestEncoding(boolean)}
     * and {@link #setForceResponseEncoding(boolean)}.
     * @see #setForceRequestEncoding(boolean)
     * @see #setForceResponseEncoding(boolean)
     */
    public void setForceEncoding(boolean forceEncoding) {
        this.forceRequestEncoding = forceEncoding;
        this.forceResponseEncoding = forceEncoding;
    }

    /**
     * Set whether the configured {@link #setEncoding encoding} of this filter
     * is supposed to override existing request encodings.
     * <p>Default is "false", i.e. do not modify the encoding if
     * {@link javax.servlet.http.HttpServletRequest#getCharacterEncoding()}
     * returns a non-null value. Switch this to "true" to enforce the specified
     * encoding in any case.
     * @since 4.3
     */
    public void setForceRequestEncoding(boolean forceRequestEncoding) {
        this.forceRequestEncoding = forceRequestEncoding;
    }

    /**
     * Return whether the encoding should be forced on requests
     * @since 4.3
     */
    public boolean isForceRequestEncoding() {
        return this.forceRequestEncoding;
    }

    /**
     * Set whether the configured {@link #setEncoding encoding} of this filter
     * is supposed to override existing response encodings.
     * <p>Default is "false", i.e. do not modify the encoding.
     * Switch this to "true" to enforce the specified encoding
     * for responses in any case.
     * @since 4.3
     */
    public void setForceResponseEncoding(boolean forceResponseEncoding) {
        this.forceResponseEncoding = forceResponseEncoding;
    }

    /**
     * Return whether the encoding should be forced on responses.
     * @since 4.3
     */
    public boolean isForceResponseEncoding() {
        return this.forceResponseEncoding;
    }


    @Override
    protected void doFilterInternal(
            HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        String encoding = getEncoding();
        if (encoding != null) {
            if (isForceRequestEncoding() || request.getCharacterEncoding() == null) {
                request.setCharacterEncoding(encoding);//解决POST请求中文乱码问题
            }
            if (isForceResponseEncoding()) {
                response.setCharacterEncoding(encoding);
            }
        }
        filterChain.doFilter(request, response);
    }

}

在web.xml该过滤器是这样配置的:需要设置的两个参数为encoding、forceEncoding,分别设置字符集及是否设置字符集,该filter也非常简单

    <!-- 解决POST请求的中文乱码问题 -->
    <filter>
        <filter-name>CharacterEncodingFilter</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>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

有的时候,看到源码才知道一些真理,所有才知道spring只是利用request.setCharacterEncoding(this.encoding);帮助我们处理了POST方式的乱码问题,碰到GET方式的提交,还是会出现乱码。

注意:自从Tomcat5.x开始,就对GET方式和POST方式的提交分别给予不同的处理方式[所以在二阶段学习的时候就应该严格区分get和post请求的处理情况,养成良好的习惯,想想是否做的到]。POST方式是利用request.setCharacterEncoding()来进行设置编码,如果没有设置的话,就是按照默认的ISO-8859-1来进行编码;GET方式提交总是利用默认的ISO-8859-1来进行编码参数。


中文乱码解决方案

1.利用String[也是最常用的方式]--查阅JDK API

String username = new String(username.getBytes("ISO-8859-1"), "UTF-8"); //通过默认的编码获取到byte[],然后进行UTF-8再次编码  

2.在tomcat中的server.xml进行配置URIEncoding="UTF-8"

<Connector URIEncoding="UTF-8" port="8080" protocol="HTTP/1.1"  
                 connectionTimeout="20000"  
                 redirectPort="8443" /> 

增加属性 URIEncoding="UTF-8" 一劳永逸解决GET请求的乱码问题

3.使用JavaScript对传递的参数进行编码

Js编码的几种方式区别:

1.window.escape()与HttpUtility.UrlEncodeUnicode()编码格式一样:将一个汉字编码为%uxxxx格式
不会被window.escape编码的字符有:@ _ - . * / +  这与http://www.w3school.com.cn/js/jsref_escape.asp上的解释不符合

2.window.encodeURIComponent()[我推荐使用这种方式]与HttpUtility.UrlEncode()编码格式一样:将一个汉字编码为%xx%xx%xx的格式
不会被window.encodeURIComponent编码的字符有:'  (  )  *  -  . _   ! ~   这与http://www.w3school.com.cn/js/jsref_encodeURIComponent.asp解释相符合
不会被HttpUtility.UrlEncode编码的字符有:'  (  )  *  -  .  _  ! 相比较而言,HttpUtility.UrlEncode比window.encodeURIComponent多一个 ~ 编码

3.不会被window.encodeURI编码的字符有: -  _  .  !  * (  )  ;  /  ?  :  @  &  =  ,  #,与encodeURIComponent对比,发现encodeURI不对:;/?:@&=+,  #,与encodeURIComponent对比,发现encodeURI不对:;/?:@&=+,#这些用于分隔 URI 组件的标点符号进行编码

window.encodeURIComponent() 推荐方式

事例演示说明

JavaScript代码:
window.self.location="searchbytext.action?searchtext="+encodeURIComponent(encodeURIComponent(seartext));
java后台处理代码:
searchtext=java.net.URLDecoder.decode(searchtext,"UTF-8");
/*
为什么要两次编码的原因:
后台java代码给searchtext赋值的时候,本身已经使用了一次解码,不过解码的结果依然不对。
所以我们可以在页面上进行两次编码操作,这样后台自动的那次就可以抵消掉一次,
然后在使用searchtext=java.net.URLDecoder.decode(searchtext,"UTF-8");
进行一次解码就好了。【这种方式还是用的比较多的,我个人使用的比较少】
*/
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,653评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,321评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,833评论 0 324
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,472评论 1 266
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,306评论 4 357
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,274评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,658评论 3 385
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,335评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,638评论 1 293
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,697评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,454评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,311评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,699评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,986评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,254评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,647评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,847评论 2 335

推荐阅读更多精彩内容