apache+tomcat 乱码问题

apache+tomcat 乱码问题

1.tomcat里面,HTTP请求设置 URIEncoding="UTF-8",页面只要是用UTF-8编码,这里设置就可以了,
案例1:
我尝试给apache加上AddDefaultCharset ISO-8859-1,没有。改成AddDefaultCharset UTF-8,也没用。改成AddDefaultCharset off,还是没有用。
这么看来,问题不在apache的配置这里了。

那么问题在那里呢??!我晕掉了。
后来我想起了一个问题,请求是apche转发给tomcat的,那么会不会是apache转到tomcat的时候,出现的乱码呢?
于是,我把tomcat配置转接接口的配置改了一下
代码如下:

Java代码 
1.<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8"/> 
 
成功了。

2.tomcat与apache连接的时候,需要将apache的编码方式与tomcat一致,不然在用中文传递的时候产生乱码,
解决办法1:在与apache连接的 ajp里面进行设置编码方式:URIEncoding="UTF-8",达到统一就可以了,
解决办法2:在apache里面设置编码方式:

服务器端:
======
修改httpd.conf (在Redhat中放置的位置为/etc/httpd/conf/)
查找:
AddDefaultCharset ISO-8859-1
改成:
#AddDefaultCharset ISO-8859-1
AddDefaultCharset off

这种方式关掉了服务器的默认语言的发送,这样仅凭html文件头中设置的语言来决定网页语言。

很多文章都说通过修改为 AddDefaultCharset GB2312 把缺省语言改成GB2312来解决中文乱码,确实GB2312内码的网页可以正常显示了,但这并非万全之策。因为当你的网页内码不是GB2312,就算你在网页用下面的meta指定了正确的语言,如ISO8859-1,也不会解码为ISO8859-1,因为Apache已经先你一步将GB2312指定为网页的语言了

解决办法三:
在代码中进行转码,apache过来的是iso8859-1.
JSP页面:
1.var params = ....  
2.params = encodeURI(params);   //进行URLencode。
3.url = url + '&' + params;  
4.... 

JAVA里面进行解码:
1.public static Map<String, String> decodeRequestToMap(HttpServletRequest request) {  
2.    Map<String, String> m = new HashMap<String, String>();  
3.    Enumeration<String> e = request.getParameterNames();  
4.    try {  
5.        while(e.hasMoreElements()) {  
6.            String k = e.nextElement();  
7.            String value = URLDecoder.decode(request.getParameter(k), "UTF-8");  
8.            m.put(k, value);  
9.        }  
10.    } catch (UnsupportedEncodingException e1) {  
11.        if (log.isErrorEnabled()) {  
12.            log.error("不可能不支持UTF-8的啊!", e1);  
13.        }  
14.    }  
15.    return m;  
16.} 

案例2:
1.jsp 页面中的JS代码:  
2. 
3.function  removeFile(str){  
4.     var title = document.getElementById("title").value;  
5.     window.location.href="<%=request.getContextPath()%>/removeAnnualReport.do?   title="+encodeURI(encodeURI(title));  
6. }  
7.注意:使用两次encodeURI 对title 进行转换  

Java代码 
1. java中转码:  
2.   
3.this.getRequest().setCharacterEncoding("UTF-8");  
4.title =URLDecoder.decode(title, "UTF-8");  
5. 
6.URLDecoder 进行解码 
java中转码:
this.getRequest().setCharacterEncoding("UTF-8");
title =URLDecoder.decode(title, "UTF-8");

使用URLDecoder 进行解码

经以上测试,成功。记录一下。



猜你喜欢

转载自xdy2008.iteye.com/blog/1263913