解决java中Post请求,在拦截器取requestBody数据后,controller层接收的数据为空,原因:因为是流。java中的流也是只能读一次,因为读完之后,position就到末尾了。
解决方案如下:
- 创建一个类BodyReaderHttpServletRequestWrapper,继承HttpServletRequestWrapper,重写getInputStream和getReader方法,把request请求体继续往下传。
public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {
private final byte[] body;
public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
String sessionStream = getBodyString(request);
body = sessionStream.getBytes(Charset.forName("UTF-8"));
}
public String getBodyString(){
return new String(body,Charset.forName("UTF-8"));
}
/**
* 获取请求Body
*
* @param request
* @return
*/
private String getBodyString(final ServletRequest request) {
StringBuilder sb = new StringBuilder();
InputStream inputStream = null;
BufferedReader reader = null;
try {
inputStream = cloneInputStream(request.getInputStream());
reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
/**
* Description: 复制输入流
*
* @param inputStream
* @return
*/
public InputStream cloneInputStream(ServletInputStream inputStream) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
try {
while ((len = inputStream.read(buffer)) > -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
byteArrayOutputStream.flush();
}
catch (IOException e) {
e.printStackTrace();
}
InputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
return byteArrayInputStream;
}
@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();
}
public boolean isFinished() {
return false;
}
public boolean isReady() {
return false;
}
public void setReadListener(ReadListener readListener) {
}
};
}
}
- 过滤器中,检验条件通过的url,将request请求重新创建自定义的请求对象,并往下传递
public class RequestFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) servletResponse;
HttpServletRequest req = (HttpServletRequest) servletRequest;
String origin = req.getHeader("Origin");
System.out.println("***************跨域过滤器**************");
if(!org.springframework.util.StringUtils.isEmpty(origin)) {
res.addHeader("Access-Control-Allow-Origin", origin);
}
res.addHeader("Access-Control-Allow-Methods", "*");
res.addHeader("Access-Control-Allow-Credentials", "true");
res.addHeader("Access-Control-Allow-Headers", "*");
if (req.getMethod().equals("OPTIONS")) {
res.setStatus(HttpServletResponse.SC_OK);
return;
}
String uri = ((HttpServletRequest) servletRequest).getRequestURI();
if(uri != null && containRegisterUri(uri)) {
//解决POST请求从stream只能获取一次数据问题
BodyReaderHttpServletRequestWrapper requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) servletRequest);
filterChain.doFilter(requestWrapper, servletResponse);
}else{
filterChain.doFilter(servletRequest, servletResponse);
}
}
/**
* 请求uri是否在指定列表中
* @param curUri
* @return
*/
private boolean containRegisterUri(String curUri){
String[] arr = new String[]{
"xxx/xxxx",
"xxx/yyyy"
};
List<String> urls = Arrays.asList(arr);
for(String url : urls){
if(curUri.contains(url)){
return true;
}
}
return false;
}
@Override
public void destroy() {
}
}
- 拦截器对request对象进行转换为自定义的请求对象,获取requestBody中请求体参数。值得注意的是:拦截器中是可以注入交给spring管理的对象(如serviceImpl对象),对业务逻辑进行控制是否继续往下执行。
@Slf4j
public class FilterPointInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
WordFilterPoint annotation = null;
// 检查请求的handler中是否有FilterPoint注解,方法级别的注解
if(handler instanceof HandlerMethod) {
annotation = ((HandlerMethod) handler).getMethodAnnotation(FilterPoint.class);
}
if (annotation != null) {
log.info("***************FilterPoint**************************");
//get相关请求参数
Map parameterMap = request.getParameterMap();
Map reqMap = new HashMap<String,Object>();
Set<Map.Entry<String,String[]>> entry = parameterMap.entrySet();
Iterator<Map.Entry<String,String[]>> it = entry.iterator();
while (it.hasNext()){
Map.Entry<String,String[]> me = it.next();
reqMap.put(me.getKey(),me.getValue()[0]);
}
//post请求,body中的json参数
if("POST".equalsIgnoreCase(request.getMethod())) {
BodyReaderHttpServletRequestWrapper requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
String bodyString = requestWrapper.getBodyString();
if (JSONUtils.mayBeJSON(bodyString)) {
Map postMap = JSON.parseObject(bodyString, Map.class);
String paramString = JSON.toJSONString(reqMap);
log.info("****** POST paramString={}", paramString);
reqMap.putAll(postMap);
}
}
}
return true;
}
}
- 最后,请求在拦截器中处理过后,controller层中也可以正常接收到参数。Ps:特意在此记录一下解决的过程,有更好的建议请提出、改正!