为了多次读取ServletInputStream引发的一系列惨案


1.因为服务器和app之间传输方式是JSON

格式如下

{

 head:null

body:null

token:xxxxxxxxxxxxxxxxxxxxx

}

所以想在服务端写个拦截器或者filter先读取token,来验证身份.但是如果前置拦截,那么在springMVC里的参数控制器就会读取不到,导致@RequestBody 这个注解的参数不起作用.

原因在于ServletInputStream已经在前置拦截器里读取过一次,在接下来的ArgumentHandler里读取的时候就不能再读了,导致取不到数据而无法赋值.

于是写了下面的filter来让ServletInputStream来多次读取

先写个request

public class MyHttpRequest extends HttpServletRequestWrapper {
	private static Logger log=Logger.getLogger(MyHttpRequest.class);
    private  byte[] bytes;
    /**
     * @param request {@link javax.servlet.http.HttpServletRequest} object.
     * @throws IOException 
     */
    public MyHttpRequest(HttpServletRequest request) throws IOException {
        super(request);
        bytes= IOUtils.toByteArray( request.getInputStream());      
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        return new DelegatingServletInputStream(byteArrayInputStream);
    }
    @Override
    public BufferedReader getReader() throws IOException {
    	return new BufferedReader(new InputStreamReader(getInputStream()));
    }

以上内容是先读取出来,然后放到一个byte[]里,以后每次拿流的时候就可以再新建一个关于Byte[]的流.

然后再写一个filter

public class MyFilter implements Filter{

	@Override
	public void destroy() {
		
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest) req;
		MyHttpRequest myrequest=new MyHttpRequest(request);
		chain.doFilter(myrequest, res);
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}
	
}

在web.xml里配置一下,试试效果,非常不错.可以多次读取了,

但是,我去

在post请求下,request.getParamter这种东西又不起作用了.

原因在于我们重写的那个request是默认调用父类的super.getparamter方法,而super.getparamter又依赖于super.getInputStream,但是在我们重写的request里的构造方法里,第一句话就老request注入到super里,然后下一句话就把老的request的流给读了,导致我们调用super.getparameter的时候遇到了一个空的流,我靠!

我靠!

解决思路:自己解决

package com.hrhs.jyj.filter;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.mock.web.DelegatingServletInputStream;

public class MyHttpRequest extends HttpServletRequestWrapper {
	private static Logger log = Logger.getLogger(MyHttpRequest.class);
	private byte[] bytes;
	private String body;
	private Map<String, List<String>> map;
	private int readMap=0;
	private String queryString;
	/**
	 * @param request
	 *            {@link javax.servlet.http.HttpServletRequest} object.
	 * @throws IOException
	 */
	public MyHttpRequest(HttpServletRequest request) throws IOException {
		super(request);
		bytes = IOUtils.toByteArray(request.getInputStream());
		queryString = request.getQueryString();
		
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
		return new DelegatingServletInputStream(byteArrayInputStream);
	}

	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(getInputStream()));
	}

	@Override
	public String getParameter(String name) {
		log.info("走了getParameter");
		return super.getParameter(name);
	}

	@Override
	public Map<String, String[]> getParameterMap() {
		log.info("走了getParameterMap");
		return super.getParameterMap();
	}

	@Override
	public Enumeration<String> getParameterNames() {
		log.info("走了getParameterNames");
		return super.getParameterNames();
	}
	//暂时先改写这一个,其他的也可以修改
	@Override
	public String[] getParameterValues(String name) {
		log.info("走了getParameterValues");
		try {
			Map<String, List<String>> nameVals = doParameter();
			List<String> list = nameVals.get(name);
			if(list!=null&&list.size()>0){
				return list.toArray(new String[]{});
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return new String[]{};
	}
	//这里获取所有参数值的map
	public Map<String, List<String>> doParameter() throws UnsupportedEncodingException {
		if(readMap==0){
			//这里把post里的参数和地址栏参数结合到一起,然后解析
			body = new String(bytes, getCharacterEncoding())+"&"+queryString;
			String[] nameVals = body.split("&");
			map = new HashMap<String, List<String>>();
			for (String nameVal : nameVals) {
				String name = nameVal.split("=")[0];
				String val = nameVal.split("=")[1];
				if (map.containsKey(name)) {
					List<String> vals = map.get(name);
					vals.add(val);
					map.put(name, vals);
				} else {
					List<String> vals = new ArrayList<String>();
					vals.add(val);
					map.put(name, vals);
				}
			}
			readMap=1;
		}
		return map;
		
	}
}





智能推荐

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告