I'd like to create URLs based on the URL used by the client for the active request. Is there anything smarter than taking the current HttpServletRequest
object and it's getParameter...()
methods to rebuilt the complete URL including (and only) it's GET parameters.
Clarification: If possible I want to resign from using a HttpServletRequest
object.
Instead of using
RequestContextHolder
directly, you can also useServletUriComponentsBuilder
and its static methods:ServletUriComponentsBuilder.fromCurrentContextPath()
ServletUriComponentsBuilder.fromCurrentServletMapping()
ServletUriComponentsBuilder.fromCurrentRequestUri()
ServletUriComponentsBuilder.fromCurrentRequest()
They use
RequestContextHolder
under the hood, but provide additional flexibility to build new URLs using the capabilities ofUriComponentsBuilder
.Example:
Well there are two methods to access this data easier, but the interface doesn't offer the possibility to get the whole URL with one call. You have to build it manually:
I don't know about a way to do this with any Spring MVC facilities.
If you want to access the current Request without passing it everywhere you will have to add a listener in the web.xml:
And then use this to get the request bound to the current Thread:
Java's URI Class can help you out of this:
If you need the URL till hostname and not the path use Apache's Common Lib
StringUtil
, and from URL extract the substring till third indexOf/
.Example: If fullURL is
https://example.com/path/after/url/
then Output will behttps://example.com
in jsp file:
You can also add a
UriComponentsBuilder
to the method signature of your controller method. Spring will inject an instance of the builder created from the current request.Using the builder you can directly start creating URIs based on the current request e.g. modify path segments.
See also UriComponentsBuilderMethodArgumentResolver