您好,登錄后才能下訂單哦!
本篇內容主要講解“如何解決為了多次讀取ServletInputStream引發的一系列問題”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“如何解決為了多次讀取ServletInputStream引發的一系列問題”吧!
多次讀取ServletInputStream引發的問題
因為服務器和app之間傳輸方式是JSON
于是寫了下面的filter來讓ServletInputStream來多次讀取
解決思路:自己解決
ServletInputStream重復讀取問題
直接貼代碼了,親測能用
格式如下
{ head:null body:null token:xxxxxxxxxxxxxxxxxxxxx }
所以想在服務端寫個攔截器或者filter先讀取token,來驗證身份.但是如果前置攔截,那么在springMVC里的參數控制器就會讀取不到,導致@RequestBody 這個注解的參數不起作用.
原因在于ServletInputStream已經在前置攔截器里讀取過一次,在接下來的ArgumentHandler里讀取的時候就不能再讀了,導致取不到數據而無法賦值.
先寫個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; } }
本來是想實現tomcat的acess_log打印post請求參數。吐槽一下,tomcat功能和nginx差了好幾條街。網上找了個方法,用tomcat的filter來實現。
但是,寫filter的時候,發現了ServletInputStream重復讀取問題。
網上找個幾個方法,都不能直接用。綜合網上的資料,根據自己的理解,終于能完美運行了。
首先要寫個BufferHttpServletRequestWrapper類,用來復制HttpServletRequest request。
import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; public class BufferHttpServletRequestWrapper extends HttpServletRequestWrapper { private final byte[] body; public BufferHttpServletRequestWrapper(HttpServletRequest request) throws IOException { super(request); InputStream is = request.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buff[] = new byte[ 1024 ]; int read; while( ( read = is.read( buff ) ) > 0 ) { baos.write( buff, 0, read ); } body = baos.toByteArray(); } @Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(getInputStream())); } @Override public ServletInputStream getInputStream() throws IOException { final ByteArrayInputStream bais = new ByteArrayInputStream(body); return new ServletInputStream() { @Override public int read() throws IOException { return bais.read(); } }; } }
然后filter實現如下:
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; 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; /** * Servlet Filter implementation class PostDataDumperFilter */ public class PostDataDumperFilter implements Filter { private FilterConfig filterConfig = null; /** * Default constructor. */ public PostDataDumperFilter() { // TODO Auto-generated constructor stub } /** * @see Filter#destroy() */ public void destroy() { this.filterConfig = null; } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (filterConfig == null) return; //備份HttpServletRequest ServletRequest requestWrapper = null; if(request instanceof HttpServletRequest) { requestWrapper = new BufferHttpServletRequestWrapper((HttpServletRequest) request); } //使用流 InputStream reader = requestWrapper.getInputStream(); ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(100); int i =0; byte [] b = new byte[100]; while((i = reader.read(b))!= -1){ byteOutput.write(b, 0, i); } request.setAttribute("post", new String(byteOutput.toByteArray())); // pass the request along the filter chain if(null == requestWrapper){ chain.doFilter(request, response); } else { chain.doFilter(requestWrapper, response); } } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { this.filterConfig = fConfig; } }
到此,相信大家對“如何解決為了多次讀取ServletInputStream引發的一系列問題”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。