package information;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.springframework.util.StreamUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {
private byte[] requestBody = null;
// 傳入是JSON格式 轉換成JSONObject
public JSONObject getRequestBody() throws UnsupportedEncodingException {
return JSON.parseObject((new String(requestBody, "UTF-8")));
}
public void setRequestBody(JSONObject jsonObject) throws UnsupportedEncodingException {
this.requestBody = jsonObject.toJSONString().getBytes("UTF-8");
}
public MyHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
try {
requestBody = StreamUtils.copyToByteArray(request.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public ServletInputStream getInputStream() throws IOException {
if (requestBody == null) {
requestBody = new byte[0];
}
final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody);
return new ServletInputStream() {
@Override
public int read() throws IOException {
return bais.read();
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener listener) {
}
};
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
}
代碼如上。
自定義過濾器攔截到作為一個整體的JSON格式的請求以后,如果要讀取內容就必須調用request.getInputStream()獲取輸入流來讀取。但是這個方法在定義的時候因為不能調用reset方法,所以實際上調用一次以后,流讀取到了結束無法再次讀取,導致以后的請求無法獲取到參數。
這里使用了一個自定義的HttpServletRequest來保存一下請求的內容,之后doChain連鎖把這個丟進去就好了。
封裝了JSONObject的轉換,直接調用對應方法就可以修改請求參數內容了。
參考:http://huangqiqing123.iteye.com/blog/2237263
