Filter字符编码的处理.

阅读更多

package com.syaccp.filter;

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.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
 
/**
   web.xml 配置
  
 
  CharacterFilter
  
   com.syaccp.filter.CharacterFilter
  

  
   encoding
   UTF-8
  

 

 
  CharacterFilter
  /*
 

 */
public class CharacterFilter implements Filter {

 //编码格式
 private String encoding = null;

 public void destroy() {
  this.encoding = null;
 }
 
    public void doFilter(ServletRequest request, ServletResponse response, 
            FilterChain chain) throws IOException, ServletException { 
    
     HttpServletRequest httpRequest = (HttpServletRequest) request; 
        if (httpRequest.getMethod().equals("GET")) { 
            request = new Request(httpRequest);  
        }
       
        request.setCharacterEncoding(this.encoding);
 response.setContentType("text/html; charset="+this.encoding);
        chain.doFilter(request, response);  
    } 

 public void init(FilterConfig filterconfig) throws ServletException {
  this.encoding = filterconfig.getInitParameter("encoding");
 }

 /**
  * 扩展HttpServletRequestWrapper类
  */
 class Request extends HttpServletRequestWrapper {
  public Request(HttpServletRequest request) {
   super(request);
  }

  /**
   * 转换由表单读取的数据的内码, 从ISO字符转到utf-8
   */
  public String toChina(String input) {
   try {
    byte[] bytes = input.getBytes("ISO8859-1");
    return new String(bytes, encoding);
   } catch (Exception ex) {
   }
   return null;
  }

  private HttpServletRequest getHttpServletRequest() {
   return (HttpServletRequest) super.getRequest();
  }

  /**
   * 读取参数列表,修正了中文问题 重写javax.getParameterValues,截获jsp传过来的参数并用toChina()转成中文
   */
  @Override
  public String[] getParameterValues(String name) {
   String values[] = getHttpServletRequest().getParameterValues(name);
   if (values != null) {
    for (int i = 0; i < values.length; i++) {
     values[i] = toChina(values[i]);
    }
   }
   return values;
  }

  @Override
  public String getParameter(String name) {
   // TODO Auto-generated method stub
   return toChina(getHttpServletRequest().getParameter(name));
  }
  
  

  
 }

}

你可能感兴趣的:(过滤器,字符编码)