Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a Spring @RequestMapping having a @pathVariable containing "/"?

I am doing the following request from the client:

/search/hello%2Fthere/

where the search term "hello/there" has been URLencoded.

On the server I am trying to match this URL using the following request mapping:


@RequestMapping("/search/{searchTerm}/") 
public Map searchWithSearchTerm(@PathVariable String searchTerm) {
// more code here 
}

But I am getting error 404 on the server, due I don't have any match for the URL. I noticed that the URL is decoded before Spring gets it. Therefore is trying to match /search/hello/there which does not have any match.

I found a Jira related to this problem here: http://jira.springframework.org/browse/SPR-6780 .But I still don't know how to solve my problem.

Any ideas?

Thanks

like image 851
yeforriak Avatar asked Feb 25 '10 14:02

yeforriak


People also ask

What is the use of @PathVariable annotation in Spring rest?

Simply put, the @PathVariable annotation can be used to handle template variables in the request URI mapping, and set them as method parameters.

What is @PathVariable annotation in Spring boot?

The @PathVariable annotation is used to extract the value of the template variables and assign their value to a method variable. A Spring controller method to process above example is shown below; @RequestMapping("/users/{userid}", method=RequestMethod.

What is @RequestMapping annotation in Spring?

RequestMapping annotation is used to map web requests onto specific handler classes and/or handler methods. @RequestMapping can be applied to the controller class as well as methods. Today we will look into various usage of this annotation with example and other annotations @PathVariable and @RequestParam .

What is the use of @PathVariable annotation?

The @PathVariable annotation is used to extract the value from the URI. It is most suitable for the RESTful web service where the URL contains some value. Spring MVC allows us to use multiple @PathVariable annotations in the same method. A path variable is a critical part of creating rest resources.


1 Answers

There are no good ways to do it (without dealing with HttpServletResponse). You can do something like this:

@RequestMapping("/search/**")  
public Map searchWithSearchTerm(HttpServletRequest request) { 
    // Don't repeat a pattern
    String pattern = (String)
        request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);  

    String searchTerm = new AntPathMatcher().extractPathWithinPattern(pattern, 
        request.getServletPath());

    ...
}
like image 103
axtavt Avatar answered Sep 28 '22 10:09

axtavt