Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to get the current URL in Spring MVC?

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.

like image 292
Koraktor Avatar asked Sep 29 '09 06:09

Koraktor


People also ask

What is URL mapping in Spring MVC?

Tags:spring mvc | url mapping. In Spring MVC application, the SimpleUrlHandlerMapping is the most flexible handler mapping class, which allow developer to specify the mapping of URL pattern and handlers explicitly. The SimpleUrlHandlerMapping can be declared in two ways.

Which of the following annotations will help us to read the value from the request URL?

We can use @RequestMapping with @RequestParam annotation to retrieve the URL parameter and map it to the method argument.


1 Answers

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(HttpServletRequest request) {     return request.getRequestURL().toString() + "?" + request.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() 
like image 55
Daff Avatar answered Oct 01 '22 22:10

Daff