3

In my spring webservice I'm trying to get the url of my application like "http://localhost:8080/mycontext". My service does not contain any HttpServletRequest var, so I can I get it ?

anais1477
  • 466
  • 1
  • 17
  • 36
  • 1
    You might need to add HttpServletRequest as a parameter. https://stackoverflow.com/questions/1490821/whats-the-best-way-to-get-the-current-url-in-spring-mvc – Alain-Michel Chomnoue N Jun 21 '17 at 12:40
  • 1
    `HttpServletRequest` can be injected by Spring in your controller's methods, just add it in the parameters. – sjahan Jun 21 '17 at 12:47

1 Answers1

8

You can get the current request via the RequestContextHolder like:

ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest req = sra.getRequest();     
req.getContextPath();
req.getPathInfo();

Or you can just inject it via Spring into your service:

private @Autowired HttpServletRequest request;
Jeroen
  • 3,076
  • 1
  • 17
  • 16