Robert Munteanu
Robert Munteanu

Reputation: 68308

Building a HTTP link inside a Spring bean which is not a Controller

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

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?

Upvotes: 2

Views: 352

Answers (2)

skaffman
skaffman

Reputation: 403551

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.

Upvotes: 1

Grzegorz Oledzki
Grzegorz Oledzki

Reputation: 24271

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.

Upvotes: 2

Related Questions