spring控制器块调用

pcww981p  于 2021-07-23  发布在  Java
关注(0)|答案(0)|浏览(220)

假设我有一个简单的Spring控制器。

@PostMapping
public ResponseEntity<?> myMethod(@RequestBody MyDto input) {
   ...
}

我想实现一种机制,检查mydto对象中的某个值是否与请求附带的特定http报头的值匹配,如果不匹配,则必须拒绝请求。
我试着用一个拦截器来实现这个功能,但是看起来您无法读取body请求两次(当请求到达控制器时导致异常)。
我也尝试过使用contentcachingrequestwrapper,但是.getcontentasbyarrays(…)提供空数组:

ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(req);
byte[] buf = wrappedRequest.getContentAsByteArray();

更新1
如前所述,我尝试使用filter,但结果是相同的,空字节数组:

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(req);

    byte[] buf = wrappedRequest.getContentAsByteArray();
    //buf is empty

    chain.doFilter(wrappedRequest, response);
}

更新2移动线路

chain.doFilter(wrappedRequest, response);

在得到body之前,它可以正常工作,但是阻止请求为时已晚,因为它已经命中了控制器。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题