How to get Url of my web application but without HttpServletRequest

Viewed 91

I want to get the current url of my application in Java Spring boot. But the problem is, I want to get that from the util class and not from Controller. I tried to get this from HttpServletRequest but I am unable to import its package into my util class.

Please help me to get the URL of my website which should not be hardcoded. Or if there is a way to use HttpServletRequest into my util class.

1 Answers

If you need the url for example in your service you can annotate with @Autowired an HttpServletRequest as follow:

@Service
public class MyService {
    @Autowired
    private HttpServletRequest httpServletRequest;



    public String getCurrentUrl() {
        return httpServletRequest.getURL().toString();
    }
}

You can use the same technique in any Component, so any object created by spring. It works if you are executing code directly from an http request. It means that you can't use it for example in a different thread started from the thread receiving the http request.

Related