|
首先看是從什么地方開始出現(xiàn)的亂碼,只要統(tǒng)一編碼,就不會(huì)出現(xiàn)亂碼,下面以u(píng)ft-8(個(gè)人認(rèn)為最好)為例,詳細(xì)說明:
1、如果亂碼是從jsp頁面出現(xiàn)的,jsp頭部頁面加上:
<%@ page language="Java" pageEncoding="UTF-8" %>
在head標(biāo)簽中加上標(biāo)簽。
2、如果亂碼是在servlet中出現(xiàn)的,則有兩種方法:
一種是在每個(gè)servlet中doget和doPost方法頭部加上
request.setCharacterEncoding(“UTF-8″);
第二種最保險(xiǎn),一勞永逸,是專門寫一個(gè)過濾器類,也稱國際化,類名為SetCharacterEncodingFilter內(nèi)容如下
復(fù)制代碼 代碼如下:
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中加上如下代碼:
復(fù)制代碼 代碼如下:
<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數(shù)據(jù)庫的問題了
1)保證建立數(shù)據(jù)庫的時(shí)候數(shù)據(jù)庫編碼選擇的是utf-8,最好在每個(gè)表中也指定編碼格式,mysql默認(rèn)是latin1
2)如果mysql版本是4.x以上,數(shù)據(jù)庫中還是出現(xiàn)亂碼,有以下兩種解決方法:
一種是在連接數(shù)據(jù)庫的代碼中指定編碼方式:
復(fù)制代碼 代碼如下:String url = “jdbc:mysql://localhost:3306/test2?autoReconnect=true&useUnicode=true&characterEncoding=gbk&mysqlEncoding=utf8″ ;
如果還是不行的話就是用
復(fù)制代碼 代碼如下:show variables like ‘collation_%';
這個(gè)命令來查看默認(rèn)字符集,如果不是utf-8的話在my.ini(windows)或者是my.cnf(linux)將相應(yīng)的編碼修改成utf8之后重啟mysql服務(wù)器就ok了
jsp技術(shù):jsp和servlet操作mysql中文亂碼問題的解決辦法,轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請第一時(shí)間聯(lián)系我們修改或刪除,多謝。