HttpServletRequest 自行添加parameter参数

写文章之前、首先感谢该大神的文章,也算是再此基础上进行的修改吧。

地址是:点击打开链接 http://www.importnew.com/19023.html


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

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

1.加了一个过滤器,对父类ServletRequest 进行转换为子类,并将请求数据拿出来、开始解析裸奔

2.添加子类:ParameterRequestWrapper并HttpServletRequestWrapper进行继承,添加addAllParameters 及重写其他参数addParameter

3.将本次需要存放的参数添加到map中,然后将map通过HttpServletRequestWrapper 中重写addAllParameters 添加进去。

直接放代码

ParameterRequestWrapper 类

import java.util.ArrayList;
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 params = new HashMap();

    @SuppressWarnings("unchecked")
    public ParameterRequestWrapper(HttpServletRequest request) {
        // 将request交给父类,以便于调用对应方法的时候,将其输出,其实父亲类的实现方式和第一种new的方式类似
        super(request);
        //将参数表,赋予给当前的Map以便于持有request中的参数
        this.params.putAll(request.getParameterMap());
    }
    //重载一个构造方法
    public ParameterRequestWrapper(HttpServletRequest request , Map 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(MapotherParams) {//增加多个参数
        for(Map.Entryentry : otherParams.entrySet()) {
            addParameter(entry.getKey() , entry.getValue());
        }
    }


    public void addParameter(String name , Object value) {//增加参数
        if(value != null) {
        	if(value instanceof ArrayList){
        		String value1 = String.valueOf(value).substring(1,String.valueOf(value).length());
             	value = value1.substring(0,value1.length()-1);
             	params.put(name , new String[] {(String)value});
        	}
        	else 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;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



public class ParameterRequestFileter implements Filter {
	
	private static final Logger log = LoggerFactory.getLogger(ParameterRequestFileter.class);
	
	public FilterConfig config;
	
    private static Field requestField;
    
    private static Field parametersParsedField;
    
    private static Field coyoteRequestField;
    
    private static Field parametersField;
    
    private static Field hashTabArrField;
    
    private static String REQUEST_METOOD = "POST";
    
    private Field[] declaredFields = null;
   
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		try {
            Class clazz = Class.forName("org.apache.catalina.connector.RequestFacade");
            requestField = clazz.getDeclaredField("request");
            requestField.setAccessible(true);


            parametersParsedField = requestField.getType().getDeclaredField("parametersParsed");
            parametersParsedField.setAccessible(true);


            coyoteRequestField = requestField.getType().getDeclaredField("coyoteRequest");
            coyoteRequestField.setAccessible(true);


            parametersField = coyoteRequestField.getType().getDeclaredField("parameters");
            parametersField.setAccessible(true);

            declaredFields = parametersField.getType().getDeclaredFields();
            if(declaredFields.length > 0){
            	for (Field field : declaredFields) {
					if("paramHashStringArray".equals(field.getName())){//tomcat6的属性
						hashTabArrField = field;
					} 
					if("paramHashValues".equals(field.getName())){//tomcat7的属性
						hashTabArrField = field;
					}
				}
            }
            hashTabArrField.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
		
		this.config = filterConfig;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		 HttpServletRequest hrequest = (HttpServletRequest)request;
		 ParameterRequestWrapper parameterRequestWrapper = new ParameterRequestWrapper(hrequest);
		 Map map = getRequestMap(request);
	      if(map != null) {
	    	  if(hrequest.getMethod() == REQUEST_METOOD){//只添加post类型的请求数据
	    		  
		    	  Map ruleMap = (Map)xxx;//将要存放的值
		    	  if(null != ruleMap){
		    		  map.putAll(ruleMap);  
		    	  } 
	    	  }
	      }
	      parameterRequestWrapper.addAllParameters(map);
	      chain.doFilter(parameterRequestWrapper, response);
	}

	@SuppressWarnings("unchecked")
    private Map getRequestMap(ServletRequest request) {
        try {
            Object innerRequest = requestField.get(request);
            parametersParsedField.setBoolean(innerRequest, true);
            Object coyoteRequestObject = coyoteRequestField.get(innerRequest);
            Object parameterObject = parametersField.get(coyoteRequestObject);
            return (Map)hashTabArrField.get(parameterObject);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return Collections.emptyMap();
        }
    }
	
	@Override
	public void destroy() {
		  this.config = null;
	}

}

然后直接通过request进行getparameter获取该属性的值旧可以了。

本文章主要是为了做个标记,后期查阅使用、时间有限,组织语言不是特别精确,相信大概懂基础的都可以看明白。

你可能感兴趣的:(JAVA)