因为流只能读取一次,有时候我们需要对流进行处理或者校验,可以使用这种方法。
自定义RequestWrapper
public class RequestWrapper extends HttpServletRequestWrapper {
/**
* 缓存下来的HTTP body
*/
private byte[] body;
public RequestWrapper(HttpServletRequest request) throws IOException {
super(request);
body = StreamUtils.copyToByteArray(request.getInputStream());
}
/**
* 重新包装输入流
* @return
* @throws IOException
*/
@Override
public ServletInputStream getInputStream() throws IOException {
InputStream bodyStream = new ByteArrayInputStream(body);
return new ServletInputStream() {
@Override
public int read() throws IOException {
return bodyStream.read();
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener readListener) {}
};
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
}
重新DispatcherServlet中的方法
public class MyDispatcherServlet extends DispatcherServlet {
@Override
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
super.doDispatch(new RequestWrapper(request), response);
}
}
在配置类中申明
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private UserRoleInterceptor roleInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(roleInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/guestAudit/**");
}
@Bean
@Qualifier(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public DispatcherServlet dispatcherServlet() {
return new MyDispatcherServlet();
}
}
在拦截器中读取流
/**
* 拦截器(将系统用户转成流程引擎用户)
*/
@Slf4j
@Component
public class UserRoleInterceptor implements HandlerInterceptor {
@Autowired
private IWlUserRoleService iWlUserRoleService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
//校验系统标识、业务标识
byte[] bodyBytes = StreamUtils.copyToByteArray(request.getInputStream());
String body = new String(bodyBytes, request.getCharacterEncoding());
JSONObject jsonObject = JSON.parseObject(body);
String systemCode = (String) jsonObject.get("systemCode");
String bizCode = (String) jsonObject.get("bizCode");
if(StrUtil.isBlank(systemCode) || StrUtil.isBlank(bizCode)){
throw new YkException("系统标识或业务标识参数缺失");
}
//通过拦截器将系统用户同步到流程引擎用户
WlUserRoleEntity roleUserInfo = iWlUserRoleService.getRoleUserInfo(systemCode, bizCode);
if(roleUserInfo != null){
return true;
}
iWlUserRoleService.saveUserRoleInfo(systemCode, bizCode);
return true;
}
}