views:

619

answers:

1

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.

+4  A: 

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:

public static String makeUrl(HttpServleRequest request)
{
    return request.getRequestURL().toString() + "?" + req.getQueryString();
}

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:

<listener>
 <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

And then use this to get the request bound to the current Thread:

((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest()
Daff
Ok, this is a similar approach to what I've done so far. But I'm searching for a way to do this without actually using the `HttpServletRequest` object. This is because I'm using several helper classes / methods and I don't want to pass the request object every time.
Koraktor
Ok, I know what you mean and added the info you need to access the current request without passing it around.
Daff
Thanks for the reminder about the listener. I'm still new to Spring (and Java web development in general). I'm now using your code in combination with Spring Security's `UrlUtils`. Works like a charm.
Koraktor