简体   繁体   中英

How to get website url path in springboot

I want to get the url of a domain in my springboot application: eg https://www.website.com/

I have tried something like this:

 // I pass this as a parameter on my controller method
 HttpServletRequest req;

 // get the absolute path
 String path = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort(); 

I think request.getRequestURL() what you are looking for. But in most of the cases you won't get correct URL. Because most of cases application servers are behind the Gateways, and in that cases when the request reaches to the application server, it is through the Gateway and you will get Gateway URL in that cases. Because it will work as proxy server. So better solution would be asking for that in header (if you have multiple clients) or have that in config file or if using container, make it a container variable.

You can check this link, that can reply your question:

String baseUrl = ServletUriComponentsBuilder.fromRequestUri(request)
      .replacePath(null)
      .build()
      .toUriString();

https://huongdanjava.com/get-base-url-in-controller-in-spring-mvc-and-spring-boot.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM