您的位置:首页 > 运维架构 > Tomcat

解决Tomcat出现中文乱码问题

2012-09-18 11:34 281 查看
如果使用的是Tomcat服务器,在提交过程中,如果提交内容中含有中文,经常会出现中文乱码问题,下面从两个方面解决该问题。

一:中文无法显示

    有些JSP中,中文根本无法显示,这种情况下,通常的原因是,没有把文件头上的字符集设置为中文字符集,一定要保证头文件上写明:

<%@ page contentType="text/html;charset=gb2312" %>      or     <%@ page pageEncoding="gb2312" %>

(其中字符集可以为 "GBK" , "GB2312" , "UTF-8" ,"GB18030")

二:提交过程中显示乱码

在表单提交过程中,如果含有中文字符串,服务器默认将其认为ISO-8859-1编码,而网页上显示GB2312,不能兼容。有三种解决办法。

(1)

...
<%
String stu_name = request.getParameter("stuname");   //假设表单中有一个名为stuname的文本输入框
stu_name = new String(stu_name.getBytes("ISO-8859-1"),"GB2312");
...
%>
...


此方法缺点是必须对每一个字符串进行转码,很麻烦。

(2)

...
<%
request.setCharacterEncoding("GB2312"); //该方法必须在取值之前设置
String stuname = request.getParameter("stuname");
...
%>
...


此方法缺点是必须对每个页面进行request的设置,也很麻烦。

(3)

利用过滤器。

自定义类实现javax.servlet.Filter接口

public class EncodingFilter implements Filter{

public void init(FilterConfig filterConfig) throws ServletException {

}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {

//将ServletRequest和ServletResponse分别强制转换成HttpServletRequest和HttpServletResponse
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse = (HttpServletResponse)response;

//调用HttpServletRequest的方法setCharacterEncoding()
httpRequest.setCharacterEncoding("GB2312");

//传递给下一个过滤器
chain.doFilter(httpRequest, httpResponse);
}

public void destroy() {
}
}


在web.xml中

<filter>
<filter-name>encoding</filter-name>
<filter-class>zjut.tsw.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>

*代表拦截所有的请求
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息