如何解决Java WEB应用中的乱码问题(3)

  例如对于用户端请求数据中以UTF-8字符集进行URLEncoding的数据,servlet需要进行如下方式的解码:


 view plaincopy to clipboardprint?
  String opt = request.getParameter("opt");
  if (opt!=null && !"".equals(opt)) {
  opt = new String(opt.getBytes("ISO-8859-1"), "UTF-8");
  }
  String opt = request.getParameter("opt");
  if (opt!=null && !"".equals(opt)) {
  opt = new String(opt.getBytes("ISO-8859-1"), "UTF-8");
  }


  为了避免这种额外的编码/解码处理,也就是说让服务器了解到用户端在URLEncoding时所使用的字符集,从而直接进行相应字符集的URLDecoding处理,不同的HTTP服务器提供了不同的解决方案。

  以Tomcat为例,Tomcat自动解码request-line的处理方式由Tomcat的配置文件server.xml指定。在server.xml中的Connector标签中提供了URIEncoding标签属性,只要为其指定解码用的字符集,Tomcat就会自动解码request-line中经过application/x-www-form-urlencoded编码处理的数据。例如:


<Connector connectionTimeout="40000" port="8080" protocol="HTTP/1.1" 
      
  URIEncoding="UTF-8" redirectPort="8443"/>


  Tomcat自动解码request-body的处理方式是设置request的characterEncoding值。如:


  request.setCharacterEncoding("UTF-8");


  但是这一操作必须提前在filter中完成,在servlet中使用此方法已经不起作用了。filter的例子如下:


 view plaincopy to clipboardprint?
  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 CharacterEncodingFilter implements Filter {
  private String encoding;
  public CharacterEncodingFilter() {
  encoding = null;
  }
  public void destroy() {
  encoding = null;
  }
  public void doFilter(ServletRequest request, ServletResponse response,
  FilterChain chain) throws IOException, ServletException {
  request.setCharacterEncoding(encoding);
  chain.doFilter(request, response);
  }
  public void init(FilterConfig filterConfig) throws ServletException {
  encoding = filterConfig.getInitParameter("encoding");
  if (encoding == null || "".equals(encoding)) {
  encoding = "UTF-8";
  }
  }
  }
  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 CharacterEncodingFilter implements Filter {
  private String encoding;
  public CharacterEncodingFilter() {
  encoding = null;
  }
  public void destroy() {
  encoding = null;
  }
  public void doFilter(ServletRequest request, ServletResponse response,
  FilterChain chain) throws IOException, ServletException {
  request.setCharacterEncoding(encoding);
  chain.doFilter(request, response);
  }
  public void init(FilterConfig filterConfig) throws ServletException {
  encoding = filterConfig.getInitParameter("encoding");
  if (encoding == null || "".equals(encoding)) {
  encoding = "UTF-8";
  }
  }
  }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwpdjw.html