第一步:创建一个请求的包装类packagecn.gzsxt.basic.filter;importjava.util.Enumeration;importjava.util.Map;importjava.util.Vector;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletRequestWrapper;public class NullValueHandlerRequestWrapper extendsHttpServletRequestWrapper {private MapparameterMap;public void setParameterMap(MapparameterMap) {this.parameterMap =parameterMap;
}publicNullValueHandlerRequestWrapper(HttpServletRequest request) {super(request);
}
@Overridepublic EnumerationgetParameterNames() {
Vector vector = new Vector(parameterMap.keySet());returnvector.elements();
}
@OverridepublicString getParameter(String name) {
String[] results=parameterMap.get(name);return results[0];
}
@Overridepublic MapgetParameterMap() {return this.parameterMap;
}
@OverridepublicString[] getParameterValues(String name) {return this.parameterMap.get(name);
}
}
第二步:实现过滤器调用包装后的请求packagecn.gzsxt.basic.filter;importjava.io.IOException;importjava.util.HashMap;importjava.util.Iterator;importjava.util.Map;importjava.util.Map.Entry;importjava.util.Set;importjavax.servlet.Filter;importjavax.servlet.FilterChain;importjavax.servlet.FilterConfig;importjavax.servlet.ServletException;importjavax.servlet.ServletRequest;importjavax.servlet.ServletResponse;importjavax.servlet.http.HttpServletRequest;public class NullvalueHandlerFilter implementsFilter{
@Overridepublic void init(FilterConfig filterConfig) throwsServletException {
}
@Overridepublic voiddoFilter(ServletRequest request, ServletResponse response, FilterChain chain)throwsIOException, ServletException {//获得所有字段
Map parameterMap = new HashMap<>(request.getParameterMap());
Set> entrySet =parameterMap.entrySet();
Iterator> iterator =entrySet.iterator();while(iterator.hasNext()) {
Entry entry =iterator.next();if (entry.getValue()!=null) {for(int i=0;i
iterator.remove();
}
}
}
}//parameterMap就会将空字符串转成null.//注意:request对象是无法修改表单数据的!!ServletRequest对象是容Tomcat产生的,我们有没有办法new创建.
NullValueHandlerRequestWrapper wrapper =newNullValueHandlerRequestWrapper((HttpServletRequest)request);
wrapper.setParameterMap(parameterMap);//获得重写后的请求
chain.doFilter(wrapper, response);
}
@Overridepublic voiddestroy() {
}
}