package com.accphr.util; import java.io.IOException; import java.util.Iterator; import java.util.Map; 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; /** * * 字符集过滤器 * */ public class CharacterEncodingFilter implements Filter { /* 设置的字符集 */ private String encoding = "UTF-8"; public void destroy() { } @SuppressWarnings("unchecked") public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 处理服务器到客户端 response.setContentType("text/html;charset=" + this.encoding); // 处理客户端到服务器 HttpServletRequest req = (HttpServletRequest) request; String s = req.getMethod();// 获得表单提交方式 if (s.equalsIgnoreCase("post")) { req.setCharacterEncoding(this.encoding); } else if (s.equalsIgnoreCase("get")) { Map<String, String[]> map = (Map<String, String[]>) req .getParameterMap(); Iterator<String[]> it = map.values().iterator(); while (it.hasNext()) { String[] paramValues = it.next(); for (int i = 0; i < paramValues.length; i++) { byte[] b = paramValues[i].getBytes("ISO-8859-1"); paramValues[i] = new String(b, this.encoding); } } } chain.doFilter(request, response); } public void init(FilterConfig config) throws ServletException { String encoding = config.getInitParameter("encoding"); if (StringUtils.isNotBlank(encoding)) { this.encoding = StringUtils.trimToBlank(encoding); } } }
最近下载更多