笔记如下
-
web.xml
作用于全servlet请求
GenericEncodingFilter
public class GenericEncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp= (HttpServletResponse) response;
if ("post".equals(req.getMethod())) {
req.setCharacterEncoding("UTF-8");
}
//包装类
MyHttpServletRequestWrapper myrequest = new MyHttpServletRequestWrapper(req);
chain.doFilter(myrequest, resp);//执行,放行
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
class MyHttpServletRequestWrapper extends HttpServletRequestWrapper{
private HttpServletRequest request;
public MyHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
this.request = request;
}
@Override
public String getParameter(String name) {
Map<String,String[]> map = getParameterMap();
//获得对应 values 数组
String[] values = map.get(name);
if(values!=null){
//返回数组的第一个元素
return values[0];
}
return null;
}
@Override
public String[] getParameterValues(String name) {
Map<String,String[]> map = getParameterMap();
//获得对应 values 数组
String[] values = map.get(name);
return values;
}
//默认的是false, 表示没有 被 解码 过
private boolean hasBeenEncoded= false;
@Override
public Map<String, String[]> getParameterMap() {
String method = request.getMethod();
if ("post".equalsIgnoreCase(method)) {
//进来说明是post请求方法
try {
request.setCharacterEncoding("UTF-8");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}else {
//说明是get
//拿到有乱码的map
Map<String, String[]> map = request.getParameterMap();
//遍历map
Set<String> keys = map.keySet();
if(!hasBeenEncoded){
hasBeenEncoded = true;
for (String key : keys) {
//当前是乱码的
String[] values = map.get(key);
for (int i = 0; i < values.length; i++) {
try {
values[i] = new String(values[i].getBytes("iso8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
return map;
}
return super.getParameterMap();
}
}