在我的Spring Boot(2.1.4)应用程序中,我需要使用拦截器的RequestEntity
方法访问preHandle
。不幸的是,我似乎无法获得它的实例。
我的代码基本上是这样的:
@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注入Controller,我似乎都无法访问(传入)请求的RequestEntity
。我试图将其@Autowire
插入拦截器,但无济于事。
有什么方法可以访问它?
答案 0 :(得分:0)
您可以在preHandle方法中使请求实体执行类似的操作
HttpEntity requestEntity = ((HttpEntityEnclosingRequest) request).getEntity();
希望这对您有帮助
答案 1 :(得分:0)
如果要拦截preHandle
中的标头,而不是requestEntity.getHeaders()
,可以使用:
requestServlet.getHeaderNames();
此方法具有:
/**
* Returns an enumeration of all the header names this request contains. If
* the request has no headers, this method returns an empty enumeration.
* <p>
* Some servlet containers do not allow servlets to access headers using
* this method, in which case this method returns <code>null</code>
*
* @return an enumeration of all the header names sent with this request; if
* the request has no headers, an empty enumeration; if the servlet
* container does not allow servlets to use this method,
* <code>null</code>
*/
public Enumeration<String> getHeaderNames();
您将拥有请愿书的所有标题名称。 使用每个标题名称,您可以访问每个标题的值:
requestServlet.getHeader(headerName);
此方法可以访问:
/**
* Returns the value of the specified request header as a
* <code>String</code>. If the request did not include a header of the
* specified name, this method returns <code>null</code>. If there are
* multiple headers with the same name, this method returns the first head
* in the request. The header name is case insensitive. You can use this
* method with any request header.
*
* @param name
* a <code>String</code> specifying the header name
* @return a <code>String</code> containing the value of the requested
* header, or <code>null</code> if the request does not have a
* header of that name
*/
public String getHeader(String name);