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 ?
Asked
Active
Viewed 5,006 times
3
-
1You 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 Answers
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
-
Thank you ! I did it with private @Autowired HttpServletRequest request; – anais1477 Jun 21 '17 at 13:08