[求救]jsp连接mysql的中文问题
对于页面编码,我这样设置<%@ page contentType="text/html;charset=UTF-8" %>
整个页面不出现一个中文,都放在Resource_zh_CN.properties,并经过native2ascii转换.
这样调用<fmt:message key="page.login.title" />
这一切都可以正常.可是连接到mysql中,我这样
<value>jdbc:mysql://localhost:3306/course?useUnicode=true&characterEncoding=UTF-8</value>
也试过characterEncoding=GB2312或GBK,可是读出来的数据总要经过这样才能正常显示
new String(buffer.getBytes("ISO-8859-1"),"GB2312");
后来我还试过改MYSQL的配置
原来是这样的
default-character-set=latin1
我改成
default-character-set=gbk (也试过utf8)
可是这样改后,我连在命令中向表里插入带中文的记录都不行,然后试试在网页表单插入,结果是乱码.
我好郁闷啊!!!!!网上关于这方面的资料很多,可又不尽相同,我试过几种都不成功.
哪位有成功经验的,给个方案吧!
先谢谢啦! 1.mysql的字符集设置为gb2312
2.连接mysql时使用如下语句:"jdbc:mysql://yourhost:3306/yourdatabase?useUnicode=true&characterEncoding=GBK"
3.在页面使用:<%@ page contentType="text/html;charset=gb2312"%>
4.添加一个filter进行编码过滤。
(1)。写个filter类
public class SetCharacterEncodingFilter implements Filter {
protected String encoding = null;
protected FilterConfig filterConfig = null;
protected boolean ignore = true;
public void init(FilterConfig filterConfig) throws ServletException {
// TODO 自动生成方法存根
//使用配置的方法从web.xml中读入编码信息,避免硬编码。
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
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;
}
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO 自动生成方法存根
if (ignore || (request.getCharacterEncoding() == null)) {
String encoding = selectEncoding(request);
if (encoding != null) {
//正是通过这句代码实现的。
request.setCharacterEncoding(encoding);
}
}
// Pass control on to the next filter
chain.doFilter(request, response);
}
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
public void destroy() {
// TODO 自动生成方法存根
this.encoding = null;
this.filterConfig = null;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
}
}
(2)。在WEB-INF文件夹下的web.xml在添加:
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>gb2312</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
[ 本帖最后由 hjack 于 2006-5-21 16:56 编辑 ] 我的做法是全部改成UTF-8,对于post获取的数据只用过滤器即可(hjack贴的代码),对于get的数据需要重编码,具体方法楼主的那个new String ×××那个就是。 谢谢两位!
虽然我的问题没有得到完全解决,但我好像知道问题所在.
我记得<<JSP2.0技术手册>>有个例子是讲解决MYSQL和JSP中文问题的,而且那时照着做是可以的,只是当时没在意.现在我去重新运行那个例子,竟然不行!我想应该是我的MYSQL或TOMCAT某些地方设置出了问题,暂时不想花太多时间去搞这个问题.我想我会慢慢发现的.
没办法,JAVA的入门就是这样,开始是CLASSPATH的问题,然后JSP就来个中文问题!呵呵~ 楼上正解。我当时面对这个问题跟你的做法一样。 建议LZ去看下unicode方面的资料,明白下各种编码转化的最底层实现
迟点我发篇我个人总结的java编程注意的中文问题。包括了参数传递啊,读取数据库,。。。
页:
[1]