gpt4 book ai didi

java - 在Interceptor中访问Spring的RequestEntity

转载 作者:行者123 更新时间:2023-12-02 06:10:58 24 4
gpt4 key购买 nike

在我的 Spring Boot (2.1.4) 应用程序中,我需要访问拦截器的 preHandle 方法中的 RequestEntity。不幸的是,我似乎无法获得它的实例。

我的代码基本上是这样的:

@RestController
@RequestMapping("/")
public class MyController
{
@GetMapping("/")
@ResponseBody
public ResponseEntity getSomething()
// public ResponseEntity getSomething(RequestEntity<String> requestEntity) // doesn't work either
{
return new ResponseEntity<String>("test", HttpStatus.OK);
}
}

和这样的拦截器:

public class MyInterceptor extends HandlerInterceptorAdapter
{
// doesn't work:
// @Autowired RequestEntity<String> requestEntity;

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception {}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}

@Override
public boolean preHandle(HttpServletRequest requestServlet, HttpServletResponse responseServlet, Object handler) throws Exception
{

// ACCESS TO org.springframework.http.RequestEntity NEEDED HERE!

// NULL POINTER EXCEPTION!
requestEntity.getHeaders();

return true;
}
}

无论我是否将RequestEntity注入(inject)到 Controller 中,我似乎都无法访问(传入)请求的RequestEntity。我尝试将其@Autowire放入拦截器中,但无济于事。

有什么办法可以访问这个吗?

最佳答案

您可以让请求实体在 preHandle 方法中执行类似的操作

 HttpEntity requestEntity = ((HttpEntityEnclosingRequest) request).getEntity();

希望这对你有帮助

关于java - 在Interceptor中访问Spring的RequestEntity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55906052/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com