import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
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;
import javax.servlet.http.HttpServletRequestWrappe r;
public class GETCharacterEncodingFilt er implements Filter {
private String charset = "UTF-8";
@Override
public void init(FilterConfig config) throws ServletException {
String temp = config.getInitParameter("charset"); // 获取配置过滤器的charset参数对应的参数值
if (temp != null && !"".equals(temp.trim())) {
try {
this.charset = Charset.forName(temp).name(); // 测试字符集是否存在
} catch (Exception e) {
this.charset = Charset.defaultCharset().name(); // 如果字符集不存在在则使用当前JVM默认字符集
}
}
}
@Override
public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
if ("get".equalsIgnoreCase(request.getMethod())) { // 判断是否为get方式提交
request = new HttpServletRequestWrappe r(request) { // 重新包装request
@Override
public Map getParameterMap() {
Map map = super.getParameterMap(); // 原始的请求参数映射
Map temp = new HashMap(); // 编码后的请求参数映射
for (String key : map.keySet()) {
temp.put(key, this.getParameterValues(key));
}
return temp;
}
@Override
public String[] getParameterValues(String name) {
String[] values = super.getParameterValues(name); // 根据name获取原始的参数值数组
String[] temp = new String[values.length]; // 编码后的参数值数组
for (int x = 0, y = values.length; x < y; x++) {
temp[x] = values[x] == null ? null : convert(values[x]);
}
return temp;
}
@Override
public String getParameter(String name) {
String value = super.getParameter(name);
return value == null ? null : convert(value);
}
private String convert(String value) { // 参数值重新编码
String temp = value.trim();
if ("".equals(temp)) {
return value;
}
try {
return new String(temp.getBytes("ISO8859-1"), charset);
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
};
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}