tags:

views:

169

answers:

2

For a bean which emails users confirmation links, I'd like to generate the URL dynamically, which means that I should know:

  • the protocol;
  • the server (virtual host) name;
  • the server port
  • the context path.

on which the application is running.

I will not be running a Controller at that time, so I'd like to retrieve this data somehow.

I've found ServletContextAware so I'm using that for the context path, but have no idea for the rest. Where can I find them?

+2  A: 

I am not really sure if you can get the server name / port number while not processing a request. On the other hand, if you are processing a request you can use the ServletRequest interface.

Grzegorz Oledzki
+1 for reality check.
Robert Munteanu
+1  A: 

You could make the bean definition request-scoped, so Spring will create a new one for every http request. You then have the option of declaring an @Autowired HttpServletRequest field, and Spring will supply it for you. You can then use that request object to build your URLs.

There are some gotcha with scoped beans (see here), but nothing serious.

skaffman
+1 for nice Spring trick.
Robert Munteanu