HttpServletRequest实现自行添加parameter参数,自定义request.setParameter()

/ java / 1 条评论 / 370浏览

众所周知:从前端传入数据项的时候、后台通过HttpServletRequest 中的getParameter对数据进行获取。但仅仅是从前端请求发送过来的请求数据,如果后台想将数据放进去,下次请求或者其他请求时使用,只能放入到setAttribute 中,下一次请求时在想使用只能从新getAttribute,getParameter恐怕是不行得了。

HttpServletRequest 只提供了getParameter ,而没有提供setParameter,太可惜。

  1. 加了一个过滤器,对父类ServletRequest 进行转换为子类,并将请求数据拿出来、开始解析裸奔
  2. 添加子类:ParameterRequestWrapper并HttpServletRequestWrapper进行继承,添加addAllParameters 及重写其他参数addParameter
  3. 将本次需要存放的参数添加到map中,然后将map通过HttpServletRequestWrapper 中重写addAllParameters 添加进去。

直接放代码

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

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中的参数
        this.params.putAll(request.getParameterMap());
    }
    //重载一个构造方法
    public ParameterRequestWrapper(HttpServletRequest request , Map<String , Object> extendParams) {
        this(request);
        addAllParameters(extendParams);//这里将扩展参数写入参数表
    }
 
    @Override
    public String getParameter(String name) {//重写getParameter,代表参数从当前类中的map获取
        String[]values = params.get(name);
        if(values == null || values.length == 0) {
            return null;
        }
        return values[0];
    }
 
    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)});
            }
        }
    }
}

过滤器 ParameterRequestFileter

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Map;
 
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;
 
//实现过滤html危险字符
public class ParameterRequestFileter implements Filter {
        @Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	private static String htmlTag(String str){
		if(StringUnit.isEmpty(str))
			return str;
		str = str.replace(">", ">");
		str = str.replace("<", "<");
		str = str.replace("'", "");
		str = str.replace("\"", "");
		return str;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)req;
		ParameterRequestWrapper requestWrapper = new ParameterRequestWrapper(request);
		HttpServletResponse response = (HttpServletResponse)resp;
		Enumeration<String> enumer = request.getParameterNames();
		while(enumer.hasMoreElements()){
			String key = enumer.nextElement();
			String[] vals = request.getParameterValues(key);
			if(vals != null && vals.length > 0){
				String strs[] = new String[vals.length];
				for(int i = 0;i < vals.length;i++){
					strs[i] = htmlTag(vals[i]);
					requestWrapper.addParameter(key, strs);
				}
			}else{
				requestWrapper.addParameter(key, vals);
			}
			
		}
		chain.doFilter(requestWrapper, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}
	
}

最后在web.xml中配置过滤器

<filter>  
     <filter-name>parameterRequestFileter</filter-name>  
     <filter-class>ParameterRequestFileter</filter-class>  
</filter>  
<filter-mapping>  
     <filter-name>parameterRequestFileter</filter-name>  
     <url-pattern>/*</url-pattern>  
</filter-mapping>  
  1. 可以用,连request.getParameterValues都实现了

    回复