死亡笔记sp:在做JSP网页中,请求表单里面的汉字怎么是乱码怎么办?

来源:百度文库 编辑:神马品牌网 时间:2024/05/05 17:00:53

Mysql与JSP网页中文乱码问题的解决方案自从以前学习JSP开始,中文乱码问题就一直不断,苦不堪言。这次在项目开始之前,我们要解决的第一个问题就是把mysql的中文乱码问题搞定。经过多天的努力,终于成功的解决了中文乱码问题,特写在这里,以备后用。

软件及环境:Windows XP(2000), j2sdk1.4.2, Tom*at 5.0.25, mysql 4.1, EMS Mysql Manager 2(方便建表,版本2.8.5.1),驱动为mysql-*onne*tor-java-3.1.4-beta-bin.jar。

目标:在该环境下,实现中文的正常显示,读取与插入数据库。

注:我只在此环境下测试通过,别的系统及不同版本未测试

要点:统一字符集(JSP页面编码,mysql建库时字符集选择,连接数据库URL,request设定等)

下面我以GBK为例讲解。如果要使用utf-8,只要在相应的GBK处换成utf-8即可

--------------------------- 步骤1 以GBK字符集建库建表 -------------------------------------

我使用EMS来建mysql的数据库及表,因为它是图形界面,方便操作(就像SQL SERVER 2000中的企业管理器一样)。

建库时,从EMS菜单中选*reate Database...新建一个数据库,Chara*terSet选gbk_bin(另一个gbk_*hinese_*i不知道与这个有什么区别,我找资料也没有找到。如果你知道,请告诉我,我补充在这里)。不要把工具栏上有一个加号和数据库模样的图标当成新建数据库了,那个新注册一个已经存在的数据库。
后面建表时,也要选择同样的字符集。

建好后,此时不要用EMS向里面插入数据,否则你看到的中文依然是乱码。

--------------------------- 步骤2 连接数据库的URL后加些参数 -------------------------------

假设我新建的数据库是testdb,那么我连接数据库的url应该为:

jdb*:mysql://lo*alhost:3306/testdb?useUni*ode=true&*hara*terEn*oding=gbk

此时要注意:如果我是把这个url写在JAVA代码中,就直接这样写。但如果是在xml配置文件中(如struts-*onfig.xml,web.xml等),要把其中的&改为&才行,否则会出错。也就是:

jdb*:mysql://lo*alhost:3306/testdb?useUni*ode=true&*hara*terEn*oding=gbk

--------------------------- 步骤3 每个JSP页面都要声明该中文字符集 ----------------------------

在每个JSP页面的最上面都加上一句

<%@ page language="java" *ontentType="text/html;*harset=GBK" %>

这样才能保证JSP页面中的中文显示正常

--------------------------- 步骤4 加一个传递参数时设定request字符集的filter类 -----------------------

因为网络中字符在传递的时候,都是统一以iso-8859-1的编码传递,所以我们必须对request重新设定字符集,才能正常显示中文。如果采用filter类来实现,我们不用在每次取中文参数时都要重新设定。

filter类的内容:

/*
* ====================================================================
*
* JavaWebStudio 开源项目
*
* Struts_db v0.1
*
* ====================================================================
*/
pa*kage *om.strutsLogin.util;

import java.io.IOEx*eption;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletEx*eption;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
* 中文过滤器
*/
publi* *lass SetChara*terEn*odingFilter implements Filter {

// ----------------------------------------------------- Instan*e Variables

/**
* The default *hara*ter en*oding to set for requests that pass through
* this filter.
*/
prote*ted String en*oding = null;

/**
* The filter *onfiguration obje*t we are asso*iated with. If this value
* is null, this filter instan*e is not *urrently *onfigured.
*/
prote*ted FilterConfig filterConfig = null;

/**
* Should a *hara*ter en*oding spe*ified by the *lient be ignored?
*/
prote*ted boolean ignore = true;

// --------------------------------------------------------- Publi* Methods

/**
* Take this filter out of servi*e.
*/
publi* void destroy() {

this.en*oding = null;
this.filterConfig = null;

}

/**
* Sele*t and set (if spe*ified) the *hara*ter en*oding to be used to
* interpret request parameters for this request.
*
* @param request The servlet request we are pro*essing
* @param result The servlet response we are *reating
* @param *hain The filter *hain we are pro*essing
*
* @ex*eption IOEx*eption if an input/output error o**urs
* @ex*eption ServletEx*eption if a servlet error o**urs
*/
publi* void doFilter(ServletRequest request, ServletResponse response,
FilterChain *hain)
throws IOEx*eption, ServletEx*eption {

// Conditionally sele*t and set the *hara*ter en*oding to be used
if (ignore || (request.getChara*terEn*oding() == null)) {
String en*oding = sele*tEn*oding(request);
if (en*oding != null)
request.setChara*terEn*oding(en*oding);
}

// Pass *ontrol on to the next filter
*hain.doFilter(request, response);

}

/**
* Pla*e this filter into servi*e.
*
* @param filterConfig The filter *onfiguration obje*t
*/
publi* void init(FilterConfig filterConfig) throws ServletEx*eption {

this.filterConfig = filterConfig;
this.en*oding = filterConfig.getInitParameter("en*oding");
String value = filterConfig.getInitParameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase("true"))
this.ignore = true;
else if (value.equalsIgnoreCase("yes"))
this.ignore = true;
else
this.ignore = false;

}

// ------------------------------------------------------ Prote*ted Methods

/**
* Sele*t an appropriate *hara*ter en*oding to be used, based on the
* *hara*teristi*s of the *urrent request and/or filter initialization
* parameters. If no *hara*ter en*oding should be set, return
* <*ode>null</*ode>.
* <p>
* The default implementation un*onditionally returns the value *onfigured
* by the <strong>en*oding</strong> initialization parameter for this
* filter.
*
* @param request The servlet request we are pro*essing
*/
prote*ted String sele*tEn*oding(ServletRequest request) {

return (this.en*oding);

}

}//EOC

该代码来自于www.javawebstudio.*om,特此感谢!

然后我们在web.xml中加一些配置,就可以了,配置如下:

<filter>
<filter-name>Set Chara*ter En*oding</filter-name>
<filter-*lass>javawebstudio.struts_db.SetChara*terEn*odingFilter</filter-*lass>
<init-param>
<param-name>en*oding</param-name>
<param-value>GBK</param-value>
</init-param>
<init-param>
<param-name>ignore</param-name>
<param-value>true</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>Set Chara*ter En*oding</filter-name>
<servlet-name>a*tion</servlet-name>
</filter-mapping>

放在web.xml的合适位置。一般在最后,<jsp-*onfig>标签之前(如果有的话)

经过以上步骤,JSP和mysql的中文显示及插入就都正常了。在STRUTS中也正常。

但是,此时如果你用EMS或mysql的命令行控制台来看表中的数据,却发现它们都是????。这是怎么回事呢?

不用担心,只要我们运行下面的这几行命令,就能看到正常的中文了!

SET *hara*ter_set_*lient = gbk;
SET *hara*ter_set_*onne*tion = gbk;
SET *hara*ter_set_database = gbk;
SET *hara*ter_set_results = gbk;
SET *hara*ter_set_server = gbk;

SET *ollation_*onne*tion = gbk_bin;
SET *ollation_database = gbk_bin;
SET *ollation_server = gbk_bin;

如果你用的是mysql的命令行,则直接输入就好。

如果是EMS,则在工具栏中有一个Show SQL Editor按钮,点一下,把上面的命令输入,再按一个"exe*ute"的按钮,就行了!

而且在这种情况下,你可以甚至可以用中文名来建数据库,表名和字段名!!!!

----------------------------------------------------------------------------------------------------

但是有一点要特别注意!

像GBK,UTF-8这样的名字,在mysql与JAVA中有不同的规定,写的时候要格外注意,否则会出错。

比如GBK,在JAVA中要写成GBK,但在mysql中要写成gbk(连接数据库的URL)

比如UTF-8,在JAVA中要写成UTF-8,但在Mysql中要写成utf8

其它的字集符也有类似的区别

1) 在每个JSP页面开头写<%@ page contentType="text/html;charset=GBK"%>
2) 用以下方法进行转码。
static public String iso2gb(String str) {
if (str != null) {
byte[] tmpbyte=null;
try {
tmpbyte=str.getBytes("ISO8859_1");}
catch (UnsupportedEncodingException e) {
System.out.println(e.getMessage());}
try {
str=new String(tmpbyte,"GBK"); }
catch(UnsupportedEncodingException e) {
System.out.println(e.getMessage());}
}
return str;
}

老生常谈的问题,就是一个编码转换问题,需要人为转化一下
public String toChinese(String strvalue) {
try{
if(strvalue==null)
return null;
else
{
strvalue = new String(strvalue.getBytes("ISO8859_1"), "GBK");
return strvalue;
}
}catch(Exception e){
return null;
}
}