您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2024/7/15 15:08:51发布32次查看
首先看是从什么地方开始出现的乱码,只要统一编码,就不会出现乱码,下面以uft-8(个人认为最好)为例,详细说明:
1、如果乱码是从jsp页面出现的,jsp头部页面加上:
96270ad319ce2fbaee2c03d41275c0d2
在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中加上如下代码:
<filter> <filter-name>setcharacterencoding</filter-name> <filter-class>com.young.filter.setcharacterencodingfilter</filter-class>//注意这里是类名,要有完整包名 <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>setcharacterencoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
这样就搞定了
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了
更多jsp和servlet操作mysql中文乱码问题的解决办法。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product