get application domain + port and path programmatically in spring?

百般思念 提交于 2021-02-11 17:51:32

问题


My website calls a rest service which is also on the same application. I don't want to change the domain of the rest address if it's hosted on a different domain name and/or port. I want to get the domain, port and application path programmatically.

If we are accessing the website like

http://example.com/article1

then I should get http://example.com

or if our address is like below

http://example.com:8080/ArticleSite/article1

then I want to get http://example.com:8080/ArticleSite

How can this be done?

I did look at the answers at

What's the best way to get the current URL in Spring MVC?

but non are getting the application path.


回答1:


Hope im not late for the party.

I had issue similar to yours, and i managed to solve first part of your question by using ServletUriComponentsBuilder.

I've been using it like this to get current server URL:

ServletUriComponentsBuilder.fromCurrentContextPath().build().toUriString();

which would return http://localhost:8080 for me

EDIT: everything i wrote will not work, i'm working on a similar issue as OP, and this fix partially worked for me, after some digging i found this question, that has already been answered:

Is possible to get web application full url from Spring service that is invoked by task?

EDIT2: this guy also says it's not possible: How do I find base URL during Spring MVC startup?



来源:https://stackoverflow.com/questions/58133490/get-application-domain-port-and-path-programmatically-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!