Get host and contextroot in class without HttpServletRequest

Daniel picture Daniel · Dec 21, 2011 · Viewed 15.2k times · Source

I´m currently creating a class for handling sending of mails. For some of these mails I need to construct links (account activation, reset password, confirmations etc).

I don´t want to hardcode the host of the links, as the host will be different for dev, test and prod. So I need to get the hostname and application context programatically in my mail class.

We are using Spring MVC in this project.

I´ll illustrate what I want with an example.

In our JSPs, we have snippets like this:

<script src="<%=request.getContextPath()%>/js/jquery-1.7.js" type="text/javascript">

In this context, request.getContextPath() will resolve to http://localhost:8080/applicationName

This is what I want for my mail class aswell.

I attempted to implement ServletContextAware in my class, thinking I would be able to use servletContext.getContextPath() with similar results. But this statement only resolves to /applicationName

So to my question: How can I get the full host and context (http://localhost:8080/applicationName) in my mail class? Is there some other interface than ServletContextAware that I can use? Help please :-)

Regards Daniel

Answer

Daniel picture Daniel · Dec 21, 2011

I did search before posting, but apparently not hard enough. This exact same question has been asked (and answered) already.

Finding your application's URL with only a ServletContext