日期:2014-05-18  浏览次数:20721 次

utf-8乱码处理!!
以下为dic_left.jsp代码片断,是utf-8编码,点击查询,会把limitTest(品名)通过js提交给dic_left.jsp,limitValue接受到值后做处理。问题是:在js里alert出来的中文是好的,但是提交给dic_left.jsp的limitValue打出来的是乱码,用什么方法可以解决,前提是要用utf-8,不能用gbk。

<%@   page   contentType= "text/html;   charset=utf-8 "   %>

<script   language= "javascript ">
function   query(){
alert(window.document.formX.limitTest.value);
window.location   = "dic_left.jsp?limitValue= "+window.document.formX.limitTest.value;
}
</script>

<form   name= "formX ">
limitValue   =   request.getParameter( "limitValue ");
System.out.println( "limitValue "+limitValue);

品名: <input   type= "test "   name= "limitTest "   value= " ">
<input   type= "button "   value= "查询 "   class= "an1 "   onClick= "query() ">
</form>

------解决方案--------------------
环境:
WindowsXP中文
Eclipse3.2.1+Myeclipse5.1.0GA
Tomcat5.5
JDK1.5.0
Hibernate3.1
Mysql5.0+ mysql-connector-java-5.0.4-bin.jar

方案:
1.集成开发环境Eclipse中设置文本文件存储编码为UTF-8。
//我想是因为….如果所做工程项目最终要在别的版本操作系统的服务器上跑,这里需要设置(未经证实)
2.数据库mysql,默认编码使用utf8;
并且创建数据库时在语句后面追加DEFAULT CHARSET=utf8;set names utf8;
//如果数据库默认编码是utf8,那这个也不是必需的吧(未经证实)
3.跟数据库连接的URL:Hibernate URL:
jdbc:mysql://127.0.0.1:3306/addressbook?useUnicode=true&characterEncoding=utf8
//如果数据库默认编码是utf8,那这个也不是必需的吧(未经证实)
4.使用过滤器,过滤器文件代码见后面附1。
<filter>
<filter-name> Set Character Encoding </filter-name>
<filter-class> org.biti.filters.SetCharacterEncodingFilter </filter-class>
<init-param>
<param-name> encoding </param-name>
<param-value> UTF-8 </param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name> Set Character Encoding </filter-name>
<url-pattern> /* </url-pattern>
</filter-mapping>
//过滤的是post还是get还没弄明白,据说只过滤器中一个,另一个见5。
5.修改Tomcat配置文件server.xml中Connector部分
<Connector port= "80 "
maxHttpHeaderSize= "8192 "
maxThreads= "150 " minSpareThreads= "25 " maxSpareThreads= "75 "
enableLookups= "false " redirectPort= "8443 " acceptCount= "100 "
connectionTimeout= "20000 " disableUploadTimeout= "true " />
加入URIEncoding= "UTF-8 "一项。
//我现在这个没乱码的就没有设置….

附1:SetCharacterEncodingFilter.java(可在Tomcat示例源码中找到)
package org.biti.filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class SetCharacterEncodingFilter implements Filter {
protected String encoding = null;
protected FilterConfig filterConfig = null;
protected boolean ignore = true;
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws