• Java web开发中使用get提交表单时的中文乱码问题


    在Java web开发中, 如果使用GET方法提交表单, 会碰到服务器端收到中文字符乱码的问题. 原因是Tomcat的配置文件中, 默认编码是iso-8859-1. 这个配置在tomcat/conf/server.xml文件里面. 默认的配置项是这样的

    
    
    

    如果能修改server.xml, 并且不用担心与其他项目冲突的话, 可以通过两种途径修改(http://wiki.apache.org/tomcat/FAQ/CharacterEncoding): 1. 在里面设置URIEncoding, Set the URIEncoding attribute on the element in server.xml to something specific (e.g. URIEncoding="UTF-8") 2. 在里面设置useBodyEncodingForURI为true, 这样Connector会根据请求的编码来决定使用哪种编码, Set the useBodyEncodingForURI attribute on the element in server.xml to true. This will cause the Connector to use the request body's encoding for GET parameters. 如果不能修改server.xml, 或者说如果修改server.xml会与其他项目冲突, 就只能在自己项目里通过其他途径处理. 1. 读取请求时, 使用这样的方法, 其中encoding是你的项目的encoding:

    		public String getUnicode(String key, String encoding, String default_value)
    		{
    			try
    			{
    				byte[] tmp = get(key).getBytes("ISO-8859-1");
    				return new String(tmp, encoding);
    			}
    			catch(Exception e) 
    			{
    				return default_value;
    			}
    		}
    

    2. 输出URL时, 需要使用编码后的中文

    "&keywords="+URLEncoder.encode(keywords, SimpleConfig.getConfig("encoding"))
    

    结合1和2就能处理中文乱码的问题.

  • 相关阅读:
    socket
    netstat
    列表
    突然发现不会写代码了
    算法资源
    bit位操作
    排序算法
    连续子数组最大和
    books
    凸优化
  • 原文地址:https://www.cnblogs.com/milton/p/4215083.html
Copyright © 2020-2023  润新知