背景
通常對安全性有要求的接口都會對請求參數做一些簽名驗證,而我們一般會把驗簽的邏輯統一放到過濾器或攔截器里,這樣就不用每個接口都去重復編寫驗簽的邏輯。
在一個項目中會有很多的接口,而不同的接口可能接收不同類型的數據,例如表單數據和json數據,表單數據還好說,調用request的getParameterMap就能全部取出來。而json數據就有些麻煩了,因為json數據放在body中,我們需要通過request的輸入流去讀取。
但問題在於request的輸入流只能讀取一次不能重復讀取,所以我們在過濾器或攔截器里讀取了request的輸入流之后,請求走到controller層時就會報錯。而本文的目的就是介紹如何解決在這種場景下遇到HttpServletRequest的輸入流只能讀取一次的問題。
注:本文代碼基於SpringBoot框架
HttpServletRequest的輸入流只能讀取一次的原因
我們先來看看為什么HttpServletRequest的輸入流只能讀一次,當我們調用getInputStream()
方法獲取輸入流時得到的是一個InputStream對象,而實際類型是ServletInputStream,它繼承於InputStream。
InputStream的read()
方法內部有一個postion,標志當前流被讀取到的位置,每讀取一次,該標志就會移動一次,如果讀到最后,read()
會返回-1,表示已經讀取完了。如果想要重新讀取則需要調用reset()
方法,position就會移動到上次調用mark的位置,mark默認是0,所以就能從頭再讀了。調用reset()
方法的前提是已經重寫了reset()
方法,當然能否reset也是有條件的,它取決於markSupported()
方法是否返回true。
InputStream默認不實現reset()
,並且markSupported()
默認也是返回false,這一點查看其源碼便知:
/**
* Repositions this stream to the position at the time the
* <code>mark</code> method was last called on this input stream.
*
* <p> The general contract of <code>reset</code> is:
*
* <ul>
* <li> If the method <code>markSupported</code> returns
* <code>true</code>, then:
*
* <ul><li> If the method <code>mark</code> has not been called since
* the stream was created, or the number of bytes read from the stream
* since <code>mark</code> was last called is larger than the argument
* to <code>mark</code> at that last call, then an
* <code>IOException</code> might be thrown.
*
* <li> If such an <code>IOException</code> is not thrown, then the
* stream is reset to a state such that all the bytes read since the
* most recent call to <code>mark</code> (or since the start of the
* file, if <code>mark</code> has not been called) will be resupplied
* to subsequent callers of the <code>read</code> method, followed by
* any bytes that otherwise would have been the next input data as of
* the time of the call to <code>reset</code>. </ul>
*
* <li> If the method <code>markSupported</code> returns
* <code>false</code>, then:
*
* <ul><li> The call to <code>reset</code> may throw an
* <code>IOException</code>.
*
* <li> If an <code>IOException</code> is not thrown, then the stream
* is reset to a fixed state that depends on the particular type of the
* input stream and how it was created. The bytes that will be supplied
* to subsequent callers of the <code>read</code> method depend on the
* particular type of the input stream. </ul></ul>
*
* <p>The method <code>reset</code> for class <code>InputStream</code>
* does nothing except throw an <code>IOException</code>.
*
* @exception IOException if this stream has not been marked or if the
* mark has been invalidated.
* @see java.io.InputStream#mark(int)
* @see java.io.IOException
*/
public synchronized void reset() throws IOException {
throw new IOException("mark/reset not supported");
}
/**
* Tests if this input stream supports the <code>mark</code> and
* <code>reset</code> methods. Whether or not <code>mark</code> and
* <code>reset</code> are supported is an invariant property of a
* particular input stream instance. The <code>markSupported</code> method
* of <code>InputStream</code> returns <code>false</code>.
*
* @return <code>true</code> if this stream instance supports the mark
* and reset methods; <code>false</code> otherwise.
* @see java.io.InputStream#mark(int)
* @see java.io.InputStream#reset()
*/
public boolean markSupported() {
return false;
}
我們再來看看ServletInputStream,可以看到該類沒有重寫mark()
,reset()
以及markSupported()
方法:
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package javax.servlet;
import java.io.IOException;
import java.io.InputStream;
/**
* Provides an input stream for reading binary data from a client request,
* including an efficient <code>readLine</code> method for reading data one line
* at a time. With some protocols, such as HTTP POST and PUT, a
* <code>ServletInputStream</code> object can be used to read data sent from the
* client.
* <p>
* A <code>ServletInputStream</code> object is normally retrieved via the
* {@link ServletRequest#getInputStream} method.
* <p>
* This is an abstract class that a servlet container implements. Subclasses of
* this class must implement the <code>java.io.InputStream.read()</code> method.
*
* @see ServletRequest
*/
public abstract class ServletInputStream extends InputStream {
/**
* Does nothing, because this is an abstract class.
*/
protected ServletInputStream() {
// NOOP
}
/**
* Reads the input stream, one line at a time. Starting at an offset, reads
* bytes into an array, until it reads a certain number of bytes or reaches
* a newline character, which it reads into the array as well.
* <p>
* This method returns -1 if it reaches the end of the input stream before
* reading the maximum number of bytes.
*
* @param b
* an array of bytes into which data is read
* @param off
* an integer specifying the character at which this method
* begins reading
* @param len
* an integer specifying the maximum number of bytes to read
* @return an integer specifying the actual number of bytes read, or -1 if
* the end of the stream is reached
* @exception IOException
* if an input or output exception has occurred
*/
public int readLine(byte[] b, int off, int len) throws IOException {
if (len <= 0) {
return 0;
}
int count = 0, c;
while ((c = read()) != -1) {
b[off++] = (byte) c;
count++;
if (c == '\n' || count == len) {
break;
}
}
return count > 0 ? count : -1;
}
/**
* Has the end of this InputStream been reached?
*
* @return <code>true</code> if all the data has been read from the stream,
* else <code>false</code>
*
* @since Servlet 3.1
*/
public abstract boolean isFinished();
/**
* Can data be read from this InputStream without blocking?
* Returns If this method is called and returns false, the container will
* invoke {@link ReadListener#onDataAvailable()} when data is available.
*
* @return <code>true</code> if data can be read without blocking, else
* <code>false</code>
*
* @since Servlet 3.1
*/
public abstract boolean isReady();
/**
* Sets the {@link ReadListener} for this {@link ServletInputStream} and
* thereby switches to non-blocking IO. It is only valid to switch to
* non-blocking IO within async processing or HTTP upgrade processing.
*
* @param listener The non-blocking IO read listener
*
* @throws IllegalStateException If this method is called if neither
* async nor HTTP upgrade is in progress or
* if the {@link ReadListener} has already
* been set
* @throws NullPointerException If listener is null
*
* @since Servlet 3.1
*/
public abstract void setReadListener(ReadListener listener);
}
綜上,InputStream默認不實現reset的相關方法,而ServletInputStream也沒有重寫reset的相關方法,這樣就無法重復讀取流,這就是我們從request對象中獲取的輸入流就只能讀取一次的原因。
使用HttpServletRequestWrapper + Filter解決輸入流不能重復讀取問題
既然ServletInputStream不支持重新讀寫,那么為什么不把流讀出來后用容器存儲起來,后面就可以多次利用了。那么問題就來了,要如何存儲這個流呢?
所幸JavaEE提供了一個 HttpServletRequestWrapper類,從類名也可以知道它是一個http請求包裝器,其基於裝飾者模式實現了HttpServletRequest界面,部分源碼如下:
package javax.servlet.http;
import java.io.IOException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.ServletRequestWrapper;
/**
* Provides a convenient implementation of the HttpServletRequest interface that
* can be subclassed by developers wishing to adapt the request to a Servlet.
* This class implements the Wrapper or Decorator pattern. Methods default to
* calling through to the wrapped request object.
*
* @see javax.servlet.http.HttpServletRequest
* @since v 2.3
*/
public class HttpServletRequestWrapper extends ServletRequestWrapper implements
HttpServletRequest {
/**
* Constructs a request object wrapping the given request.
*
* @param request The request to wrap
*
* @throws java.lang.IllegalArgumentException
* if the request is null
*/
public HttpServletRequestWrapper(HttpServletRequest request) {
super(request);
}
private HttpServletRequest _getHttpServletRequest() {
return (HttpServletRequest) super.getRequest();
}
/**
* The default behavior of this method is to return getAuthType() on the
* wrapped request object.
*/
@Override
public String getAuthType() {
return this._getHttpServletRequest().getAuthType();
}
/**
* The default behavior of this method is to return getCookies() on the
* wrapped request object.
*/
@Override
public Cookie[] getCookies() {
return this._getHttpServletRequest().getCookies();
}
從上圖中的部分源碼可以看到,該類並沒有真正去實現HttpServletRequest的方法,而只是在方法內又去調用HttpServletRequest的方法,所以我們可以通過繼承該類並實現想要重新定義的方法以達到包裝原生HttpServletRequest對象的目的。
首先我們要定義一個容器,將輸入流里面的數據存儲到這個容器里,這個容器可以是數組或集合。然后我們重寫getInputStream方法,每次都從這個容器里讀數據,這樣我們的輸入流就可以讀取任意次了。
具體的實現代碼如下:
package com.example.wrapperdemo.controller.wrapper;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;
/**
* @author 01
* @program wrapper-demo
* @description 包裝HttpServletRequest,目的是讓其輸入流可重復讀
* @create 2018-12-24 20:48
* @since 1.0
**/
@Slf4j
public class RequestWrapper extends HttpServletRequestWrapper {
/**
* 存儲body數據的容器
*/
private final byte[] body;
public RequestWrapper(HttpServletRequest request) throws IOException {
super(request);
// 將body數據存儲起來
String bodyStr = getBodyString(request);
body = bodyStr.getBytes(Charset.defaultCharset());
}
/**
* 獲取請求Body
*
* @param request request
* @return String
*/
public String getBodyString(final ServletRequest request) {
try {
return inputStream2String(request.getInputStream());
} catch (IOException e) {
log.error("", e);
throw new RuntimeException(e);
}
}
/**
* 獲取請求Body
*
* @return String
*/
public String getBodyString() {
final InputStream inputStream = new ByteArrayInputStream(body);
return inputStream2String(inputStream);
}
/**
* 將inputStream里的數據讀取出來並轉換成字符串
*
* @param inputStream inputStream
* @return String
*/
private String inputStream2String(InputStream inputStream) {
StringBuilder sb = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(inputStream, Charset.defaultCharset()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
log.error("", e);
throw new RuntimeException(e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
log.error("", e);
}
}
}
return sb.toString();
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream inputStream = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public int read() throws IOException {
return inputStream.read();
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
};
}
}
除了要寫一個包裝器外,我們還需要在過濾器里將原生的HttpServletRequest對象替換成我們的RequestWrapper對象,代碼如下:
package com.example.wrapperdemo.controller.filter;
import com.example.wrapperdemo.controller.wrapper.RequestWrapper;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* @author 01
* @program wrapper-demo
* @description 替換HttpServletRequest
* @create 2018-12-24 21:04
* @since 1.0
**/
@Slf4j
public class ReplaceStreamFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("StreamFilter初始化...");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
ServletRequest requestWrapper = new RequestWrapper((HttpServletRequest) request);
chain.doFilter(requestWrapper, response);
}
@Override
public void destroy() {
log.info("StreamFilter銷毀...");
}
}
然后我們就可以在攔截器中愉快的獲取json數據也不慌controller層會報錯了:
package com.example.wrapperdemo.controller.interceptor;
import com.example.wrapperdemo.controller.wrapper.RequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author 01
* @program wrapper-demo
* @description 簽名攔截器
* @create 2018-12-24 21:08
* @since 1.0
**/
@Slf4j
public class SignatureInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("[preHandle] executing... request uri is {}", request.getRequestURI());
if (isJson(request)) {
// 獲取json字符串
String jsonParam = new RequestWrapper(request).getBodyString();
log.info("[preHandle] json數據 : {}", jsonParam);
// 驗簽邏輯...略...
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
/**
* 判斷本次請求的數據類型是否為json
*
* @param request request
* @return boolean
*/
private boolean isJson(HttpServletRequest request) {
if (request.getContentType() != null) {
return request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE) ||
request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE);
}
return false;
}
}
編寫完以上的代碼后,還需要將過濾器和攔截器在配置類中進行注冊才會生效,過濾器配置類代碼如下:
package com.example.wrapperdemo.config;
import com.example.wrapperdemo.controller.filter.ReplaceStreamFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.Filter;
/**
* @author 01
* @program wrapper-demo
* @description 過濾器配置類
* @create 2018-12-24 21:06
* @since 1.0
**/
@Configuration
public class FilterConfig {
/**
* 注冊過濾器
*
* @return FilterRegistrationBean
*/
@Bean
public FilterRegistrationBean someFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(replaceStreamFilter());
registration.addUrlPatterns("/*");
registration.setName("streamFilter");
return registration;
}
/**
* 實例化StreamFilter
*
* @return Filter
*/
@Bean(name = "replaceStreamFilter")
public Filter replaceStreamFilter() {
return new ReplaceStreamFilter();
}
}
攔截器配置類代碼如下:
package com.example.wrapperdemo.config;
import com.example.wrapperdemo.controller.interceptor.SignatureInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author 01
* @program wrapper-demo
* @description
* @create 2018-12-24 21:16
* @since 1.0
**/
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Bean
public SignatureInterceptor getSignatureInterceptor(){
return new SignatureInterceptor();
}
/**
* 注冊攔截器
*
* @param registry registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getSignatureInterceptor())
.addPathPatterns("/**");
}
}
接下來我們就可以測試一下在攔截器中讀取了輸入流后在controller層是否還能正常接收數據,首先定義一個實體類,代碼如下:
package com.example.wrapperdemo.param;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author 01
* @program wrapper-demo
* @description
* @create 2018-12-24 21:11
* @since 1.0
**/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserParam {
private String userName;
private String phone;
private String password;
}
然后寫一個簡單的Controller,代碼如下:
package com.example.wrapperdemo.controller;
import com.example.wrapperdemo.param.UserParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 01
* @program wrapper-demo
* @description
* @create 2018-12-24 20:47
* @since 1.0
**/
@RestController
@RequestMapping("/user")
public class DemoController {
@PostMapping("/register")
public UserParam register(@RequestBody UserParam userParam){
return userParam;
}
}
啟動項目,請求結果如下,可以看到controller正常接收到數據並返回了