Tomcat 乱码的最终解决方案

Tomcat 乱码的最终解决方案

1.解决POST传送乱码的问题.
<filter>
    <filter-name>Set Character Encoding</filter-name>
    <filter-class>com.util.filters.SetCharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>Set Character Encoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

SetCharacterEncodingFilter:

package com.util.filters;

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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class SetCharacterEncodingFilter
    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 {

    // Conditionally select and set the character encoding to be used
   request.setCharacterEncoding("GBK");
    // Pass control on to the next filter
    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);

  }

}

2.解决GET方式出现乱码的方案


tomcat的server.xml中
<Connector connectionTimeout="20000" maxSpareThreads="75" maxThreads="150" minSpareThreads="25" port="8080" redirectPort="8443" uRIEncoding="UTF-8" useBodyEncodingForURI="true">
</Connector>
注意其中的useBodyEncodingForURI="true"这句是是解决问题的关键,但缺省情况下没有,自己加进去。
然后再用Filter方案解决 解决GET的问题

3.乱码字符转换 
  byte[] bytes = str.getBytes("ISO8859-1");
    String dept=new String(bytes);

AJAX
在用XMLHttpRequest发送请求时如用post方式传送数据,容易出现中文乱码问题!
在Ajax中,默认的编码方式是UTF-8,所以在服务器端用request.setCharacterEncoding("UTF-8");(对于java言,其它语言可能类似方法)设置编码即可解决大部份的编码问题!

 对于服务器端返回的XML文件在用responseXML读取时也要注意编码问题!

以下是正确的处理方法:

response.setCharacterEncoding("UTF-8");-----(1)
PrintWriter out=response.getWriter();------(2)
out.println("返回内容");

如上所示,如果1、2的先后顺序发生变化就会产生乱码!

你可能感兴趣的:(Tomcat 乱码的最终解决方案)