通过实现 Filter 接口进行项目全局编码控制

废话不多说,直接给代码:

/**
 * 
 */
package com.adam.dev.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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author adam.胡升阳
 * 创建日期 2011-5-4
 */
public class EncoderFilter implements Filter {
	private String encoding;
	
	public void init(FilterConfig config) throws ServletException {
		encoding = config.getInitParameter("Encoding");
	}
	
	/*
	 *设置数据请求响应编码格式为GBK
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		res.setContentType("text/html");
		req.setCharacterEncoding(encoding);
		res.setCharacterEncoding(encoding);
		chain.doFilter(req, res);
	}
	
	public void destroy() {
		//	 TODO Auto-generated method stub
	}

}

web.xml中配置filter如下即可:

<!-- 自定义Filter设置系统全局字符编码 -->
  	<filter>
		<filter-name>encodeFilter</filter-name>
		<filter-class>
			com.adam.dev.utils.EncoderFilter
		</filter-class>
		<init-param>
			<param-name>Encoding</param-name>
	     	<param-value>GBK</param-value>
		</init-param>
	</filter>
	<!-- 设定为全局过滤 -->
	<filter-mapping>
		<filter-name>encodeFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	

大家注意了,这个init-param标签中的 param-value 就由你自己配置了,想搞成什么编码格式就是改一改而已!


你可能感兴趣的:(String,filter,Class,encoding)