代码如下:
/** * 编码过滤器 */package com.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.HttpServletResponse;/** * @author Admin * */public class EncodingFilter implements Filter { private FilterConfig filterConfig = null; private String targetEncoding = "UTF-8";//默认系统过滤编码 private boolean isEnabled = true;//是否启用编码过滤 /** * 编码过滤 */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (this.isEnabled) {// 使用编码过滤 HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; req.setCharacterEncoding(targetEncoding); res.setCharacterEncoding(targetEncoding); } chain.doFilter(request, response); } /** * 过滤器初始化 */ public void init(FilterConfig config) throws ServletException { this.filterConfig = config; String encoding = filterConfig.getInitParameter("Encoding").trim(); this.targetEncoding = encoding.equals("")?this.targetEncoding:encoding; this.isEnabled = Boolean.valueOf(filterConfig.getInitParameter("Enabled")); } public EncodingFilter() { } public void destroy() { }}
web.xml配置:
EncodingFilter EncodingFilter com.map.pgis.popu.filter.EncodingFilter 过滤字符编码 Encoding UTF-8 是否启用编码过滤器 Enabled true EncodingFilter /EncodingFilter EncodingFilter /*