美文网首页
003.GET和POST中文乱码问题解决专题

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

作者: 胖先森 | 来源:发表于2017-04-27 13:11 被阅读0次

    有一枚学生问问了我一个问题,突然灵感爆发,他使用的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");
    进行一次解码就好了。【这种方式还是用的比较多的,我个人使用的比较少】
    */
    

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/tgigzttx.html