日期:2014-05-17  浏览次数:20897 次

jsp 中文乱码问题,求解决
数据库是mysql编码是:GB2312

JSP页面编码设置:
<%@ page language="java" contentType="text/html; charset=GBK"
pageEncoding="GBK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">

JSP和数据库显示插入的中文都是乱码,应该是JSP页面的问题,已经上网找了好几天了,都不能解决,求大虾指点!
(数据库GB2312和JSP的GBK没冲突,已经过同学实验!无乱码)

------解决方案--------------------
可以用写一个中文的过滤器:
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest req=(HttpServletRequest)request;
if("get".equalsIgnoreCase(req.getMethod())){

Map map=req.getParameterMap();
for (Iterator itr=map.values().iterator();itr.hasNext();){
String[] param=(String[])itr.next();
for (int i=0;i<param.length;i++){
param[i]=new String(param[i].getBytes("ISO-8859-1"),"UTF-8");
}

}

}else{
req.setCharacterEncoding("UTF-8");
}
response.setContentType("text/html;charset=UTF-8");

chain.doFilter(request, response);
}
------解决方案--------------------
public class ToChinese
{
public String trans(String str)
{
if(str==null)
{
str="";
}
else
{
try
{
str=(new String(str.getBytes("iso-8859-1"),"GB2312")).trim();
}
catch(Exception e)
{
e.printStackTrace(System.err);
}
}
return str; 
}
}
------解决方案--------------------
用这个试试,我以前也是,但后来就用这个解决的。
把tomcat中WEB-INF\classes\filters\下的几个文件拷到你站点相应目录下,
在web.xml中加入
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>