zoukankan      html  css  js  c++  java
  • 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就能处理中文乱码的问题.

  • 相关阅读:
    Hibernate3.3 中常见错误
    Hibernate Tools for Eclipse插件的安装和使用
    写个换房(先卖后买)退个人所得税的攻略 (转)
    Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
    用SQL删除重复记录的N种方法
    Spring中ref local与ref bean区别
    Nginx反向代理
    文件上传
    linux 进程
    pdo
  • 原文地址:https://www.cnblogs.com/milton/p/4215083.html
Copyright © 2011-2022 走看看