servlet mysql 乱码_jsp和servlet操作mysql中文乱码问题的解决办法

转载:http://www.jb51.net/article/49253.htm

首先看是从什么地方开始出现的乱码,只要统一编码,就不会出现乱码,下面以uft-8(个人认为最好)为例,详细说明:

1、如果乱码是从jsp页面出现的,jsp头部页面加上:

在head标签中加上标签。

2、如果乱码是在servlet中出现的,则有两种方法:

一种是在每个servlet中doget和doPost方法头部加上

request.setCharacterEncoding(“UTF-8″);

第二种最保险,一劳永逸,是专门写一个过滤器类,也称国际化,类名为SetCharacterEncodingFilter内容如下

代码如下:

package com.sharep.filter;//包名

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 init(FilterConfig filterConfig) throws ServletException

{

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

this.ignore = false;

}

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain) throws IOException, ServletException

{

if (ignore || (request.getCharacterEncoding() == null))

{

String encoding = selectEncoding(request);

if (encoding != null)

request.setCharacterEncoding(encoding);

}

chain.doFilter(request, response);

}

public void destroy()

{

this.encoding = null;

this.filterConfig = null;

}

protected String selectEncoding(ServletRequest request)

{

return (this.encoding);

}

}

然后在web-inf的web.xml中加上如下代码:

代码如下:

SetCharacterEncoding

com.young.filter.SetCharacterEncodingFilter//注意这里是类名,要有完整包名

encoding

UTF-8

SetCharacterEncoding

/*

这样就搞定了

3、如果还是有乱码,就是mysql数据库的问题了

1)保证建立数据库的时候数据库编码选择的是utf-8,最好在每个表中也指定编码格式,mysql默认是latin1

2)如果mysql版本是4.x以上,数据库中还是出现乱码,有以下两种解决方法:

一种是在连接数据库的代码中指定编码方式:

代码如下:

String url = “jdbc:mysql://localhost:3306/test2?autoReconnect=true&useUnicode=true&characterEncoding=gbk&mysqlEncoding=utf8″ ;

如果还是不行的话就是用

代码如下:

show variables like ‘collation_%';

这个命令来查看默认字符集,如果不是utf-8的话在my.ini(windows)或者是my.cnf(linux)将相应的编码修改成utf8之后重启mysql服务器就ok了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值