Tomcat 4.x解决方法:
获取中文:request.setCharacterEncoding("gb2312");
输出中文:<%@ page contentType="text/html;charset=gb2312" %>,必要时需要转码
Tomcat 5.x解决方法:
获取中文:
提交表单时
1)post:request.setCharacterEncoding("gb2312");
2)get:修改server.xml,在Connector中加入URIEncoding="gb2312"
如: <Connector port="80" maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
debug="0" connectionTimeout="20000"
disableUploadTimeout="true" URIEncoding="gb2312" />
或者使用useBodyEncodingForURI,使tomcat 5.x兼容tomcat 4.x
输出中文:<%@ page contentType="text/html;charset=gb2312" %>,必要时需要转码
附:Tomcat 5.x与Tomcat 4.x在解析提交表单时发生了变化,Tomcat 4.x无论是post还是get,都使用
相同的编码,而Tomcat 5.x 却把get方法单独了出来.具体可查看tomcat的source code.
get方式的处理比较好,对于post方式建议用配置过滤器的方式来解决,因为这样,配置一个地方整个系统都不用操心了。
简单说明:
web.xml
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>SetCharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
/************************/
SetCharacterEncodingFilter.java
--------------------------------------------
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;
import javax.servlet.UnavailableException;
/**
* Example filter that sets the character encoding to be used in parsing the
* incoming request
*/
public class SetCharacterEncodingFilter implements Filter {
/**
* Take this filter out of service.
*/
public void destroy() {
}
/**
* select and set (if specified) the character encoding to be used to
* interpret request parameters for this request.
*/
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 {
}
}
也可以把编码做为参数传递进去。