Доступ к SpringE RequestEntity внутри перехватчика - PullRequest
0 голосов
/ 29 апреля 2019

В моем приложении 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 в контроллер или нет, мне кажется, у меня нет возможности получить доступ к (1011) (входящему) запросу.Я пытался @Autowire перехватить его, но безрезультатно.

Есть ли способ получить к нему доступ?

Ответы [ 2 ]

0 голосов
/ 29 апреля 2019

Если вы хотите перехватить заголовки в 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);
0 голосов
/ 29 апреля 2019

Вы можете заставить Entity Entry делать что-то подобное в вашем методе preHandle

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

Надеюсь, это поможет вам

...