应用服务器tomcat编码引起的JSP中汉字传到后台乱码问题

时间:2022-05-29 11:45:46

一般JSP中汉字传到后台显示乱码的解决方案大致分为:

1.web.xml设置字符编码过滤器,后台java代码:

package com.sls.pub.utils;
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 ServletFilter
  implements Filter
{
  protected String encoding = null;

  protected FilterConfig filterConfig = null;

  protected boolean ignore = true;

  public void destroy()
  {
    this.encoding = null;
    this.filterConfig = null;
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException
  {
    if ((this.ignore) || (request.getCharacterEncoding() == null)) {
      String encoding = selectEncoding(request);
      if (encoding != null) {
        request.setCharacterEncoding(encoding);
      }
    }

    chain.doFilter(request, response);
  }

  public void init(FilterConfig filterConfig)
    throws ServletException
  {
    this.filterConfig = filterConfig;
    this.encoding = filterConfig.getInitParameter("encoding");
    String value = filterConfig.getInitParameter("ignore");
    if (value == null)
      this.ignore = true;
    else if (value.equalsIgnoreCase("true"))
      this.ignore = true;
    else if (value.equalsIgnoreCase("yes"))
      this.ignore = true;
    else
      this.ignore = false;
  }

  protected String selectEncoding(ServletRequest request)
  {
    return this.encoding;
  }
}
web.xml编写过滤器(此处允许GBK编码):
<filter>
    <filter-name>EncodingFilter</filter-name>
    <display-name>EncodingFilter</display-name>
    <description>EncodingFilter</description>
    <filter-class>com.sls.pub.utils.ServletFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>GBK</param-value>
    </init-param>
  </filter>
2.设置IDE软件(eg:myeclipse)的编码,这个方法大家可以百度一下,此处略去。
3.第三个也是大家容易忽略的问题,这里细讲一下。
我遇到的问题是,我的整个工程编码格式是GBK,JSP中在URL拼接路径访问时传递的汉字仍正常,传到后台后通过reqest.getParameter("")获取该字段后变成了乱码。我本地使用的myeclipse+tomcat。但是工程在linux环境部署的websphere应用服务器中没有乱码问题。我检查过myeclipse编码设置,然后定位到可能是应用服务器不同导致的。然后我去查tomcat的相关资料,最后发现tomcat的默认编码是iso8859-1。如果要改变其默认的编码,需要在tomcat的server.xml中,修改这段代码:
 <Connector port="8888" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
修改为:
 <Connector port="8888" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"  URIEncoding="GBK" />
问题解决...