0

I have a Rest API. Inside one of the method in Rest API, I am trying to get the URL from each request sent to the API and later performing some operation based on the URL.

Found below possibilities in stack overflow to get the URL from the incoming request.

Example 1:

@Autowired
private HttpServletRequest request;

"Inside one method"
String url = request.getRequestURL().toString();

Example 2:

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
String url = request.getRequestURL().toString();

Both will give the same result? If yes, then which one to use to get the URL from the incoming request?

Vinutha
  • 41
  • 9

1 Answers1

0

Its about how to access the HttpServletRequest. I have read in few articles that @Autowired HttpServletRequest can create issues in certain spring versions. So it would be better to go with the second approach.

You can also pass HttpServletRequest as a parameter in the API or make use of the @Context annotation to inject the HttpServletRequest instance for the current request. Its methods give access to detailed information about the request.

You can check these link1, link2, link3, link4 for more details

UPDATE To use @Context

1st Approach

public class MyService {

    @Inject // or @Autowired (both work)
    private MyRepository repository;

    @Context
    private HttpServletRequest request;

}

2nd Approach

{
   @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response get(
                 final @Context HttpServletResponse httpServletResponse) 
                 throws IOException {
 
        ServletOutputStream out = httpServletResponse.getOutputStream();
        out.print("Hello");
        out.flush();
 
        return Response.ok().build();
    }
Sachin Bose
  • 127
  • 8
  • How to use @Context annotation to inject the HttpServletRequest instance for the current request? – Vinutha Mar 29 '22 at 09:11
  • @Vinutha - I have updated my answer. Please check – Sachin Bose Mar 29 '22 at 13:35
  • `HttpServletRequest request= ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest(); String url=request.getRequestURL().toString();` if i use this then do i need to create bean of RequestContextListener in Configuration class as shown? `@Bean public RequestContextListener requestContextListener(){ return new RequestContextListener(); }` – Vinutha Mar 30 '22 at 10:59