Filter类:
public class EncodingFilter implements Filter {
private String charset = "UTF-8";
@Override
public void destroy() {}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
if(req.getMethod().equalsIgnoreCase("GET")) {
if(!(req instanceof GetRequest)) {
req = new GetRequest(req, charset);
}
} else {
req.setCharacterEncoding(charset);
}
chain.doFilter(req, response);
}
@Override
public void init(FilterConfig fConfig) throws ServletException {
String charset = fConfig.getInitParameter("charset");
if(charset != null && !charset.isEmpty()) {
this.charset = charset;
}
}
}
public class GetRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;
private String charset;
public GetRequest(HttpServletRequest request, String charset) {
super(request);
this.request = request;
this.charset = charset;
}
@Override
public String getParameter(String name) {
String value = request.getParameter(name);
if(value == null) return null;
try {
return new String(value.getBytes("ISO-8859-1"), charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public Map getParameterMap() {
Map
if(map == null) return map;
for(String key : map.keySet()) {
String[] values = map.get(key);
for(int i = 0; i < values.length; i++) {
try {
values[i] = new String(values[i].getBytes("ISO-8859-1"), charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
return map;
}
@Override
public String[] getParameterValues(String name) {
String[] values = super.getParameterValues(name);
for(int i = 0; i < values.length; i++) {
try {
values[i] = new String(values[i].getBytes("ISO-8859-1"), charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
return values;
}
}
web.xml配置: