解决Tomcat出现中文乱码问题

如果使用的是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>

*代表拦截所有的请求

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值