这是我在做的第一个项目(环境为:jdk1.6+mysql5.0.27+struts)中碰到的中文乱码问题,现总结出来供需要的人学习.如有不对的地方还请高手赐教!
1:做一个filter过滤器.代码如下:
package com.cmesn.struts.filter;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.*;
import javax.servlet.http.*;
public class CommonFilter extends HttpServlet implements Filter
{
private static final long serialVersionUID = -3432542752328407638L;
//Process the request/response pair
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException,ServletException {
//将ServletRequest对象转换HttpServletRequest
HttpServletRequest httpRequest = (HttpServletRequest) request;
//将ServletRequest对象转换HttpServletResponse
HttpServletResponse httpResponse = (HttpServletResponse) response;
//设置字符编码GBK,对应页面的编码方式;如果页面为utf-8,则下面的GBK要改为utf-8
httpRequest.setCharacterEncoding("GBK");
//调用后续过滤器
filterChain.doFilter(httpRequest, httpResponse);
}
public void init(FilterConfig arg0) throws ServletException {
// TODO 自动生成方法存根
}
}
2:在struts中的Web.xml里面配置:代码如下:
<filter>
<filter-name>charFilter</filter-name>
<filter-class>com.cmesn.struts.filter.CommonFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>charFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3:页面写法要规范,按标准写.这样可以避免从一个服务器迁移到另一个服务器的时候,可能出现的乱码问题.
jsp页面头部应该为: <%@ page language="java" import="java.util.*" content="text/html; charset=gbk""%>
4:数据库编码方式最好都设置为utf-8.
经过如上几步,一般的中文乱码问题都可以解决,如碰到特殊的还要请教高人了!