注解方式设置字符过滤器

传统方式需要在servlet中设置编码,非常繁琐又容易考虑错,所以最好设置一个字符过滤器

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.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

/**
 * 编码过滤器 采用注解的方式设置路径和参数
 * 
 * @author D丨C
 * 
 */
@WebFilter(urlPatterns = "/*", initParams = { @WebInitParam(name = "CharsetEncoding", value = "utf-8") })
public class CharacterEncodingFilter implements Filter {

	private static String encoding; // 定义变量接收初始化的值

	public CharacterEncodingFilter() {
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// 设置字符编码
		request.setCharacterEncoding(encoding);
		response.setCharacterEncoding(encoding);

		chain.doFilter(request, response);
	}

	// 初始化
	public void init(FilterConfig config) throws ServletException {
                //接收注解中的配置参数
		encoding = config.getInitParameter("CharsetEncoding");
	}

}

 

你可能感兴趣的:(工具类)