---
title: "JSP中文乱码处理"
author: "httroot"
date: "2009-06-28T22:32:52Z"
tags: []
slug: "jsp"
draft: false
lastmod: "2009-06-28T22:32:52Z"
id: 416622
url: "https://httroot.iteye.com/blog/416622"
---

1.调用JSP页面显示乱码

       通过浏览器调用JSP页面，在客户端浏览器中所有的中文内容出现乱码。

解决：

       首先确认本JSP在编辑器中保存时，使用的是GBK的编码格式，然后在JSP页面的开始部分添加 &lt;%@ pageEncoding="GBK" %&gt;就可以解决中文乱码问题。

2.调用Servlet页面显示乱码

       通过浏览器调用Servlet，Servlet在浏览器中显示内容出现乱码

解决：

       在Servlet使用response在输出内容之前，先执行response.setContentType("text/html;charset=GBK")设定输出内容的编码为GBK

 

3.Post表单传递参数乱码

       通过JSP页面、HTML页面或者Servlet中的表单元素提交参数给对应的JSP页面或者Servelt而JSP页面或者Servlet接收的中文参数值乱码。

解决：

       在接收POST提交的参数之前，使用request.setCharacterEncoding("GBK")设定接收参数的内容使用GBK编码

 

更好的解决方法是使用过滤器技术

 

       Encoding过滤器

**package** com.htt;

**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** Encoding **implements** Filter {

    **public** **void** destroy() {  }

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

           request.setCharacterEncoding("GBK");

           chain.doFilter(request, response);

    }

    **public** **void** init(FilterConfig filterConfig) **throws** ServletException { }

}    

 

Web.xml文件中的设置

&lt;filter&gt;

   &lt;filter-name&gt;encoding&lt;/filter-name&gt;

   &lt;filter-class&gt;com.htt.Encoding&lt;/filter-class&gt;

&lt;/filter&gt;

&lt;filter-mapping&gt;

   &lt;filter-name&gt;encoding&lt;/filter-name&gt;

   &lt;url-pattern&gt;/ToCh\_zn&lt;/url-pattern&gt;

&lt;/filter-mapping&gt;

 

 

4.Get方式表单传递和URI方式传递参数乱码

 解决方案

     apache-tomcat-6.0.18\\conf\\server.xml

在这个内加入一行

&lt;Connector port="8080" protocol="HTTP/1.1"

               connectionTimeout="20000"

               redirectPort="8443"  URIEncoding="GBK" /&gt;