java字符编码过滤器EncodingFilter
package com.lzcc.mvc.web.filter;
import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry;
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; import javax.servlet.http.HttpServletRequest; @WebFilter(filterName="encodingFilter",urlPatterns="/*",initParams={@WebInitParam(description="字符编码",name="charSet",value="UTF-8")}) public class EncodingFilter implements Filter{
private String charSet; @Override public void destroy() { // TODO Auto-generated method stub }
@Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletRequest request = (HttpServletRequest)req; // 判断用户的请求类型 if(request.getMethod().equalsIgnoreCase("POST")){// 如果请求是POST req.setCharacterEncoding(this.charSet);// 设置统一编码 }else{// get请求 Map<String, String[]> maps = req.getParameterMap(); Iterator<Entry<String, String[]>> iter = maps.entrySet().iterator(); while(iter.hasNext()){ Entry<String, String[]> map = iter.next(); String[] values = map.getValue(); for (int i = 0; i < values.length; i++) { values[i] = new String(values[i].getBytes("ISO-8859-1"), this.charSet); } } } chain.doFilter(req, resp);// 将请求继续传递 }
@Override public void init(FilterConfig config) throws ServletException { // TODO Auto-generated method stub this.charSet = config.getInitParameter("charSet"); } }