import java.util.Enumeration; import java.util.Map; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; /** * 思路: * 第一步:声明一个成员变量是Map。用于设置我们修改后的表单参数 * 第二部:重写request里面的获得表单参数的四个方法。设置值都是通过我们修改后参数的变量Map来获得值 * @author ranger * */ public class NullValueHandlerRequestWrapper extends HttpServletRequestWrapper { public NullValueHandlerRequestWrapper(HttpServletRequest request) { super(request); } private Map<String, String[]> parameterMap; public void setParameterMap(Map<String, String[]> parameterMap) { this.parameterMap = parameterMap; } @Override public String getParameter(String name) { String[] results = parameterMap.get(name); return results[0]; } @Override public Map<String, String[]> getParameterMap() { return this.parameterMap; } @Override public Enumeration<String> getParameterNames() { Vector<String> vector = new Vector<String>(parameterMap.keySet()); return vector.elements(); } @Override public String[] getParameterValues(String name) { return parameterMap.get(name); } }
//修改请求表单参数。
//问题:HTTPServletRequest对象并没有提供修改请求表单参数的方法。如何解决呢?
//答:Servlet技术里面提供了一个Wrapper来解决表单参数设置的。Warpper实现了重新包装一个对象设置在过滤链里面
import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; 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; public class NullvalueHandlerFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//获得所有字段 Map<String, String[]> parameterMap = new HashMap<>(request.getParameterMap()); Set<Entry<String, String[]>> entrySet = parameterMap.entrySet(); Iterator<Entry<String, String[]>> iterator = entrySet.iterator(); while (iterator.hasNext()) { Entry<String, String[]> entry = iterator.next(); if (entry.getValue()!=null) { for(int i=0;i<entry.getValue().length;i++) { if ("".equals(entry.getValue()[i])) { iterator.remove(); } } } } //parameterMap就会将空字符串转成null. //注意:request对象是无法修改表单数据的!!ServletRequest对象是容Tomcat产生的,我们有没有办法new创建. NullValueHandlerRequestWrapper wrapper =new NullValueHandlerRequestWrapper((HttpServletRequest)request); wrapper.setParameterMap(parameterMap); //获得重写后的请求 chain.doFilter(wrapper, response); } @Override public void destroy() { } }
在web.xml中加入
<filter> <filter-name>nullvalueHandlerFilter</filter-name> <filter-class>org.chu.filter.NullvalueHandlerFilter</filter-class> </filter> <filter-mapping> <filter-name>nullvalueHandlerFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>