package com.sy.entity;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class EncodingFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String method = req.getMethod().toUpperCase();
if ("POST".equals(method)) {
req.setCharacterEncoding("utf-8");
chain.doFilter(req, res);
} else if ("GET".equals(method)) {
chain.doFilter(new HttpServletRequestWrapper(req) {
@Override
public String getParameter(String name) {
String newValue = null;
String oldValue = super.getParameter(name);
if (oldValue != null) {
try {
newValue =
new String(oldValue.getBytes("ISO8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return newValue;
}
@Override
public String[] getParameterValues(String name) {
String[] oldValues = super.getParameterValues(name);
String[] newValues = new String[oldValues.length];
if (!ArrayUtils.isEmpty(oldValues)) {
for (int i = 0; i < oldValues.length; i++) {
try {
newValues[i] =
new String(oldValues[i].getBytes("ISO8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
return newValues;
}
@Override
public Map<String, String[]> getParameterMap() {
Map<String, String[]> oldMap = super.getParameterMap();
Map<String, String[]> newMap = new HashMap<>();
if (MapUtils.isNotEmpty(oldMap)) {
for (Entry<String, String[]> ele : oldMap.entrySet()) {
String key = ele.getKey();
String[] oldValues = ele.getValue();
String[] newValues = new String[oldValues.length];
if (!ArrayUtils.isEmpty(oldValues)) {
for (int i = 0; i < oldValues.length; i++) {
try {
newValues[i] =
new String(oldValues[i].getBytes("ISO8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
newMap.put(key, newValues);
}
}
return newMap;
}
}, res);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
EncodingFilter
最新推荐文章于 2020-01-09 22:35:41 发布