首页 > 代码库 > javaweb 用拦截器实现编码设置

javaweb 用拦截器实现编码设置

使用Filter 设置编码简化Servlet的开发


1. 核心代码

package com.mscncn.jsd1404;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

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

public class EncodingFilter implements Filter {
	
	private static String encoding;
	private static final String DEFAULT_CHARSET="UTF-8";
	@Override
	public void destroy() {
		System.out.println("--------destroy---------");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		System.out.println("--------doFilter---------");
		HttpServletRequest httpRequest = (HttpServletRequest) request;  
		HttpServletResponse httpResponse=(HttpServletResponse)response;
		if("GET".equals(httpRequest.getMethod())){
			EncodingHttpServletRequest wrapper = new EncodingHttpServletRequest(httpRequest, encoding);   
            chain.doFilter(wrapper, response);  
		}else{
			httpRequest.setCharacterEncoding(encoding);
			httpResponse.setContentType("text/html;charset="+encoding);
		}
	}
	private static class  EncodingHttpServletRequest extends HttpServletRequestWrapper{
		 private HttpServletRequest request;
		 public EncodingHttpServletRequest(HttpServletRequest request,String encoding) {
		   super(request);
		   this.request = request;
		 }
		 @Override
		public String getParameter(String name) {
			   String value = request.getParameter(name);
			   try {
			    value = new String(value.getBytes("iso8859-1"), encoding);
			   } catch (UnsupportedEncodingException e) {
			    e.printStackTrace();
			   }
			   return super.getParameter(name);
		}
	}
	@Override
	public void init(FilterConfig config) throws ServletException {
		 System.out.println("--------init---------");  
		 encoding = config.getInitParameter("encoding");
		 if(encoding==null||"".equals(encoding))
			 encoding=DEFAULT_CHARSET;
	}

}


 2. web.xml 中得配置

<!-- 设置全局的编码格式,针对get,post请求,默认编码为UTF-8 -->
  <filter>
  	<filter-name>characterFilter</filter-name>
  	<filter-class>com.mscncn.jsd1404.EncodingFilter</filter-class>
  	<init-param>
  		<param-name>encoding</param-name>
  		<param-value>UTF-8</param-value>
  	</init-param>
  </filter>
  <filter-mapping>
  	<filter-name>characterFilter</filter-name>
  	<!-- 拦截所有的请求,为所有的请求设置编码 -->
  	<url-pattern>/*</url-pattern>
  </filter-mapping>