统一修改表单参数(表单提交的空字符串统一转null)

1.介绍:

我们业务中有时会遇到提交的表单中某个参数为空字符串,导致后台接受的为空字符串("")而不是我们理想中的null,会增加一些不必要的处理。本文介绍通过过滤器filter统一修改表单参数。

<form method="post" action="/post">
<input type="text" name="name" value="">
<input type="submit" value="提交">
</form>

2.实现

由于自带的request.getParameterMap()不可修改。因此我们需要自定义RequestWrapper。该RequestWrapper初始化时传入原request的参数,并对参数进行筛选,删除value为空字符串("")的参数。然后过滤器filter内把原request替换为自定义的RequestWrapper。

2.1 自定义RequestWrapper

	import xxxx.common.util.MapRemoveUtils;
	
	import javax.servlet.http.HttpServletRequest;
	import javax.servlet.http.HttpServletRequestWrapper;
	import java.util.HashMap;
	import java.util.Map;
	
	public class ParameterRequestWrapper extends HttpServletRequestWrapper {
	
	    private Map<String, String[]> params = new HashMap<String, String[]>();
	
	    @SuppressWarnings("unchecked")
	    public ParameterRequestWrapper(HttpServletRequest request) {
	        // 将request交给父类,以便于调用对应方法的时候,将其输出,其实父亲类的实现方式和第一种new的方式类似
	        super(request);
	        //将参数表,赋予给当前的Map以便于持有request中的参数
	
	        Map<String, String[]> map = new HashMap<>(request.getParameterMap());
	        //删除空字符串参数
	        map=MapUtils.filterEmptyParam(map);
	        this.params.putAll(map);
	    }
	
	    @Override
	    public String getParameter(String name) {//重写getParameter,代表参数从当前类中的map获取
	        String[] values = params.get(name);
	        if (values == null || values.length == 0) {
	            return null;
	        }
	        return values[0];
	    }
	
	    @Override
	    public String[] getParameterValues(String name) {//同上
	        return params.get(name);
	    }
	
	    public void addAllParameters(Map<String, Object> otherParams) {//增加多个参数
	        for (Map.Entry<String, Object> entry : otherParams.entrySet()) {
	            addParameter(entry.getKey(), entry.getValue());
	        }
	    }
	
	
	    public void addParameter(String name, Object value) {//增加参数
	        if (value != null) {
	            if (value instanceof String[]) {
	                params.put(name, (String[]) value);
	            } else if (value instanceof String) {
	                params.put(name, new String[]{(String) value});
	            } else {
	                params.put(name, new String[]{String.valueOf(value)});
	            }
	        }
	    }
	
	    @Override
	    public Map<String, String[]> getParameterMap() {
	        return this.params;
	    }
	
	
	}

2.2 ParameterEmptyFilter

	import xxxx.ParameterRequestWrapper;
	import org.apache.commons.logging.Log;
	import org.apache.commons.logging.LogFactory;
	import org.springframework.http.HttpMethod;
	
	import javax.servlet.*;
	import javax.servlet.http.HttpServletRequest;
	import java.io.IOException;
	
	public class ParameterEmptyFilter implements Filter {
	
	
	    protected final Log logger = LogFactory.getLog(this.getClass());
	
	    @Override
	    public void init(FilterConfig filterConfig) throws ServletException {
	
	    }
	
	    @Override
	    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
	        String method = ((HttpServletRequest) request).getMethod();
	        if (HttpMethod.POST.name().equals(method)) {
	            ParameterRequestWrapper requestWrapper = new ParameterRequestWrapper((HttpServletRequest) request);
	            filterChain.doFilter(requestWrapper, response);
	            return;
	        }
	        filterChain.doFilter(request, response);
	    }
	
	    @Override
	    public void destroy() {
	
	    }
	
	}

2.3 web.xml 加入filter

         <filter>
            <filter-name>parameterEmptyFilter</filter-name>
            <filter-class>xxx.filter.ParameterEmptyFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>parameterEmptyFilter</filter-name>
            <url-pattern>/xxx/*</url-pattern>
        </filter-mapping>

2.4 MapUtils

RequestWrapper会用到,用于删除map中空key或空value。

		public class MapUtils {
		    
		    public static Map<String,Object> filterEmptyParam(Map<String,Object> param){
		        Map<String,Object> result = new HashMap<>();
		        param = Maps.filterValues(param, s -> s != null && (!(s instanceof String) || !((String) s).isEmpty()));
		        result.putAll(param);
		        return result;
		    }
		}