让tomcat支持中文cookie

这的确是一个不正常的需求,按照规范,开发者需要将cookie进行编码,因为tomcat不支持中文cookie。

但有时候,你不得不面对这样的情况,比如请求是由他人开发的软件,比如,浏览器控件发出的。

这个时候就需要修改tomcat源码来支持了。

直接上源码

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.apache.tomcat.util.http;

/**
 * Static constants for this package.
 */
public final class CookieSupport {

    // --------------------------------------------------------------- Constants
    /**
     * If set to true, we parse cookies strictly according to the servlet,
     * cookie and HTTP specs by default.
     */
    public static final boolean STRICT_SERVLET_COMPLIANCE;

    /**
     * If true, cookie values are allowed to contain an equals character without
     * being quoted.
     */
    public static final boolean ALLOW_EQUALS_IN_VALUE;

    /**
     * If true, separators that are not explicitly dis-allowed by the v0 cookie
     * spec but are disallowed by the HTTP spec will be allowed in v0 cookie
     * names and values. These characters are: \"()/:<=>[email protected][\\]{} Note that the
     * inclusion of / depends on the value of {@link #FWD_SLASH_IS_SEPARATOR}.
     */
    public static final boolean ALLOW_HTTP_SEPARATORS_IN_V0;

    /**
     * If set to false, we don‘t use the IE6/7 Max-Age/Expires work around.
     * Default is usually true. If STRICT_SERVLET_COMPLIANCE==true then default
     * is false. Explicitly setting always takes priority.
     */
    public static final boolean ALWAYS_ADD_EXPIRES;

    /**
     * If set to true, the <code>/</code> character will be treated as a
     * separator. Default is usually false. If STRICT_SERVLET_COMPLIANCE==true
     * then default is true. Explicitly setting always takes priority.
     */
    public static final boolean FWD_SLASH_IS_SEPARATOR;

    /**
     * If true, name only cookies will be permitted.
     */
    public static final boolean ALLOW_NAME_ONLY;

    /**
     * If set to true, the cookie header will be preserved. In most cases
     * except debugging, this is not useful.
     */
    public static final boolean PRESERVE_COOKIE_HEADER;

    /**
     * The list of separators that apply to version 0 cookies. To quote the
     * spec, these are comma, semi-colon and white-space. The HTTP spec
     * definition of linear white space is [CRLF] 1*( SP | HT )
     */
    private static final char[] V0_SEPARATORS = {‘,‘, ‘;‘, ‘ ‘, ‘\t‘};
    private static final boolean[] V0_SEPARATOR_FLAGS = new boolean[65536];

    /**
     * The list of separators that apply to version 1 cookies. This may or may
     * not include ‘/‘ depending on the setting of
     * {@link #FWD_SLASH_IS_SEPARATOR}.
     */
    private static final char[] HTTP_SEPARATORS;
    private static final boolean[] HTTP_SEPARATOR_FLAGS = new boolean[65536];

    static {
        STRICT_SERVLET_COMPLIANCE = Boolean.parseBoolean(System.getProperty(
                "org.apache.catalina.STRICT_SERVLET_COMPLIANCE",
                "false"));

        ALLOW_EQUALS_IN_VALUE = Boolean.parseBoolean(System.getProperty(
                "org.apache.tomcat.util.http.ServerCookie.ALLOW_EQUALS_IN_VALUE",
                "false"));

        ALLOW_HTTP_SEPARATORS_IN_V0 = Boolean.parseBoolean(System.getProperty(
                "org.apache.tomcat.util.http.ServerCookie.ALLOW_HTTP_SEPARATORS_IN_V0",
                "false"));

        String alwaysAddExpires = System.getProperty(
        "org.apache.tomcat.util.http.ServerCookie.ALWAYS_ADD_EXPIRES");
        if (alwaysAddExpires == null) {
            ALWAYS_ADD_EXPIRES = !STRICT_SERVLET_COMPLIANCE;
        } else {
            ALWAYS_ADD_EXPIRES = Boolean.parseBoolean(alwaysAddExpires);
        }

        String preserveCookieHeader = System.getProperty(
                "org.apache.tomcat.util.http.ServerCookie.PRESERVE_COOKIE_HEADER");
        if (preserveCookieHeader == null) {
            PRESERVE_COOKIE_HEADER = STRICT_SERVLET_COMPLIANCE;
        } else {
            PRESERVE_COOKIE_HEADER = Boolean.parseBoolean(preserveCookieHeader);
        }

        String  fwdSlashIsSeparator = System.getProperty(
                "org.apache.tomcat.util.http.ServerCookie.FWD_SLASH_IS_SEPARATOR");
        if (fwdSlashIsSeparator == null) {
            FWD_SLASH_IS_SEPARATOR = STRICT_SERVLET_COMPLIANCE;
        } else {
            FWD_SLASH_IS_SEPARATOR = Boolean.parseBoolean(fwdSlashIsSeparator);
        }

        ALLOW_NAME_ONLY = Boolean.parseBoolean(System.getProperty(
                "org.apache.tomcat.util.http.ServerCookie.ALLOW_NAME_ONLY",
                "false"));

        /*
        Excluding the ‘/‘ char by default violates the RFC, but
        it looks like a lot of people put ‘/‘
        in unquoted values: ‘/‘: ; //47
        ‘\t‘:9 ‘ ‘:32 ‘\"‘:34 ‘(‘:40 ‘)‘:41 ‘,‘:44 ‘:‘:58 ‘;‘:59 ‘<‘:60
        ‘=‘:61 ‘>‘:62 ‘?‘:63 ‘@‘:64 ‘[‘:91 ‘\\‘:92 ‘]‘:93 ‘{‘:123 ‘}‘:125
        */
        if (CookieSupport.FWD_SLASH_IS_SEPARATOR) {
            HTTP_SEPARATORS = new char[] { ‘\t‘, ‘ ‘, ‘\"‘, ‘(‘, ‘)‘, ‘,‘, ‘/‘,
                    ‘:‘, ‘;‘, ‘<‘, ‘=‘, ‘>‘, ‘?‘, ‘@‘, ‘[‘, ‘\\‘, ‘]‘, ‘{‘, ‘}‘ };
        } else {
            HTTP_SEPARATORS = new char[] { ‘\t‘, ‘ ‘, ‘\"‘, ‘(‘, ‘)‘, ‘,‘,
                    ‘:‘, ‘;‘, ‘<‘, ‘=‘, ‘>‘, ‘?‘, ‘@‘, ‘[‘, ‘\\‘, ‘]‘, ‘{‘, ‘}‘ };
        }
        for (int i = 0; i < 65536; i++) {
            V0_SEPARATOR_FLAGS[i] = false;
            HTTP_SEPARATOR_FLAGS[i] = false;
        }
        for (int i = 0; i < V0_SEPARATORS.length; i++) {
            V0_SEPARATOR_FLAGS[V0_SEPARATORS[i]] = true;
        }
        for (int i = 0; i < HTTP_SEPARATORS.length; i++) {
            HTTP_SEPARATOR_FLAGS[HTTP_SEPARATORS[i]] = true;
        }

    }

    // ----------------------------------------------------------------- Methods

    /**
     * Returns true if the byte is a separator as defined by V0 of the cookie
     * spec.
     */
    public static final boolean isV0Separator(final char c) {
//        if (c < 0x20 || c >= 0x7f) {
//            if (c != 0x09) {
//                throw new IllegalArgumentException(
//                        "Control character in cookie value or attribute.");
//            }
//        }

        return V0_SEPARATOR_FLAGS[c];
    }

    public static boolean isV0Token(String value) {
        if( value==null) {
            return false;
        }

        int i = 0;
        int len = value.length();

        if (alreadyQuoted(value)) {
            i++;
            len--;
        }

        for (; i < len; i++) {
            char c = value.charAt(i);
            if (isV0Separator(c)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Returns true if the byte is a separator as defined by V1 of the cookie
     * spec, RFC2109.
     * @throws IllegalArgumentException if a control character was supplied as
     *         input
     */
    public static final boolean isHttpSeparator(final char c) {
//        if (c < 0x20 || c >= 0x7f) {
//            if (c != 0x09) {
//                throw new IllegalArgumentException(
//                        "Control character in cookie value or attribute.");
//            }
//        }

        return HTTP_SEPARATOR_FLAGS[c];
    }

    public static boolean isHttpToken(String value) {
        if( value==null) {
            return false;
        }

        int i = 0;
        int len = value.length();

        if (alreadyQuoted(value)) {
            i++;
            len--;
        }

        for (; i < len; i++) {
            char c = value.charAt(i);

            if (isHttpSeparator(c)) {
                return true;
            }
        }
        return false;
    }

    public static boolean alreadyQuoted (String value) {
        if (value==null || value.length() < 2) {
            return false;
        }
        return (value.charAt(0)==‘\"‘ && value.charAt(value.length()-1)==‘\"‘);
    }

    // ------------------------------------------------------------- Constructor
    private CookieSupport() {
        // Utility class. Don‘t allow instances to be created.
    }
}

  

时间: 2024-10-31 17:43:48

让tomcat支持中文cookie的相关文章

让Tomcat支持中文文件名

--参考链接:http://blog.chinaunix.net/uid-26284395-id-3044132.html 解决问题的核心在于修改Tomcat的配置,在Server.xml文件中添加一个名为URIEncoding的属性,它用于对HTTP请求中的get方法传过来的URL进行编码.Tomcat内置的对于get协议中的URL编码是ISO-8859-1,这个字符集不能直接支持中文等双字节的信息,而中文文件的下载链接恰恰是通过get协议进行的. 打开$tomcat安装目录$/config/

tomcat支持中文文件名下载

Tomcat是Java开发者使用得较多的一个Web服务器,因为它占用资源小,运行速度快等特点,深受Java Web程序员的喜爱.不过,在使用中,由于Java中的中文问题的存在,如果不经过配置,在WEB程序中,不能直接支持具有中文文件名的文件的下载,这为Java Web程序的开发带来一定的不便.本文拟介绍一种手段,解决这个问题. 解决问题的核心在于修改Tomcat的配置,在Server.xml文件中添加一个名为URIEncoding的属性,它用于对HTTP请求中的get方法传过来的URL进行编码.

让Tomcat支持中文路径名和中文文件名

http://hdwangyi.iteye.com/blog/107709 Tomcat是Java开发者使用得较多的一个Web服务器,因为它占用资源小,运行速度快等特点,深受Java Web程序员的喜爱.不过,在使用中,由于Java中的中文问题的存在,如果不经过配置,在WEB程序中,不能直接支持具有中文文件名的文件的下载,这为Java Web程序的开发带来一定的不便.本文拟介绍一种手段,解决这个问题. 解决问题的核心在于修改Tomcat的配置,在Server.xml文件中添加一个名为URIEnc

[转载]tomcat的配置文件server.xml不支持中文注释的解决办法

原文链接:http://tjmljw.iteye.com/blog/1500370 启动tomcat失败,控制台一闪而过,打开catalina的log发现错误指向了conf/server.xml,报错信息如下: -------------------------- 05-Dec-2016 20:17:01.903 WARNING [main] org.apache.catalina.startup.Catalina.load Catalina.start using conf/server.xm

tomcat的配置文件server.xml不支持中文注释的解决办法(转载)

早上启动tomcat失败,控制台一闪而过,打开catalina的log发现错误指向了conf/server.xml,报错信息如下: -------------------------- 警告: Catalina.start using conf/server.xml: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 2 字节的 UTF-8 序列的字节 2 无效. ... ... --------

让linux(centos)支持中文文件和文件夹

一.让linux支持中文 1.将Linux的env设置了LANG=en_US.UTF-8: 2.本地的Shell客户端编码也设置成UTF-8,这样让在windows上传到linux的文件或者目录不会出现乱码: 3.重要:如果用SecureFXPortable上传时需要需要手工编辑SecrueFX的这个Session的配置文件才行(找到session文件夹) 在SecureFx中选择Options->Global Options菜单,在打开的Global Options的对话框中选择General

Tomcat get 中文乱码

乱码问题 原因: tomcat默认的在url传输时是用iso8859-1编码. 解决方案一: 在使用get传输参数时,将参数中的中文转换成url格式,也就是使用urlEncode和urlDecode来传输,使用这种方式就是把中文转换成以%开头的编码在url中传输. 使用这种方法时,要注意两点. 1.前台使用urlencode,在后台相应的使用urldecode. 2.使用urlencode的内容是参数内空.千万要注意,他是会把等于号等符号也给转换了.所以,最好是先把参数传换后再进行拼接.而不是把

Windows下面安装和配置Solr 4.9(三)支持中文分词器

首先将下载解压后的solr-4.9.0的目录里面找到lucene-analyzers-smartcn-4.9.0.jar文件, 将它复制到solr的应用程序里面D:\apache-tomcat-7.0.54\webapps\solr\WEB-INF\lib, 备注:网上很多文章使用IK中文分词器(IK_Analyzer2012_u6.jar)但是在solr-4.9.0版本中,我是一直没有配置成功.所以只能使用solr自带的中文分词器了. 在回到solr的应用程序目录(D:\Demos\Solr\

tomcat处理中文文件名的访问(乱码)

解决问题的核心在于修改Tomcat的配置,在Server.xml文件中添加一个名为URIEncoding的属性,它用于对HTTP请求中的get方法传过来的URL进行编码.Tomcat内置的对于get协议中的URL编码是ISO-8859-1,这个字符集不能直接支持中文等双字节的信息,而中文文件的下载链接恰恰是通过get协议进行的. 打开$tomcat安装目录$/config/server.xml文件,在其中找到如下代码: <Connector port="8080" protoco