1. 程式人生 > >jsp和servlet操作mysql中文亂碼問題的解決辦法

jsp和servlet操作mysql中文亂碼問題的解決辦法

inux com 過濾 國際化 出現 conf onf my.cnf pos

轉載:http://www.jb51.net/article/49253.htm

首先看是從什麽地方開始出現的亂碼,只要統一編碼,就不會出現亂碼,下面以uft-8(個人認為最好)為例,詳細說明:

1、如果亂碼是從jsp頁面出現的,jsp頭部頁面加上:
<%@ page language="java" pageEncoding="UTF-8" %>
在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中文亂碼問題的解決辦法