Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java get context url in spring service without HttpServletRequest

Tags:

java

spring

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 ?

like image 384
anais1477 Avatar asked Apr 07 '26 00:04

anais1477


1 Answers

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;
like image 108
Jeroen Avatar answered Apr 08 '26 12:04

Jeroen