近日使用ajax请求springmvc后台查询mysql数据库,页面显示中文出现乱码
最初在mybatis配置如下
<select id="querycontentbyid" resulttype = "java.lang.string" parametertype="string" > select text from news where id=#{o} </select>
其中表news的text字段为blob类型
如此查出的text值在控制台中一直显示乱码。
之后google查找相关resulttype=blob相关内容无果,遂将其改为resulttype = "java.util.map" ,且
byte[] b = (byte[]) map.get("text"); string s = new string(b,"utf-8");
打印出s,此时中文正常显示,但页面显示依旧乱码。
因此处为ajax请求,遂检查响应头信息,查出如下
content-typetext/html;charset=iso-8859-1
由于数据库中统一为编码为utf-8,故修改响应头信息
@requestmapping(value = "/querycontentbyid", method = requestmethod.get,produces = "text/plain;charset=utf-8") public @responsebody string querycontentbyid(@requestparam("id") string id) throws sqlexception, unsupportedencodingexception { map map = (map) ndrservice.querycontentbyid(id); byte[] b = (byte[]) map.get("text"); string s = new string(b,"utf-8"); return s; }
我们再来看下另外一个示例的问题
1、springmvc的controller得到的是乱码:
(1)在web.xml加上字符集过滤器:
(2)在jsp等页面上修改:charset=utf-8"和pageencoding="utf-8"
2、controller读取到的是正确的中文,但是保存到数据库后变成“??”
(1)修改数据库连接jdbc_url=jdbc:mysql://localhost:3306/mybatistest?useunicode=yes&characterencoding=utf8("&":在xml文件中表示"&")
(2)修改数据库的字符集为utf-8:打开mysql根目录下my.ini(mysql5.6为my-default.ini,要把它copy一份命名为my.ini),在下面具体位置添加(或修改):
这样设置在我这边就没什么问题了。
综述:
通常中文乱码问题都是由于字符编码设置不对导致的,我这里无论是数据库还是java文件、jsp文件,都统一成utf-8。最后问题解决了。
如对本文有疑问, 点击进行留言回复!!
SpringBoot多Module启动报错Could not transfer metadata
Hibernate项目报错:Cannot call sendError() after the response has been committed
Chrome浏览器插件万能视频下载器Video DownloadHelper
DevTools failed to load SourceMap: Could not load content
网友评论