Use part of url as argument for controller in Spring MVC

For example with the URL

foo.com/bar/99

      

99 will be available directly to the method in the controller as an argument. Controller is mapped to / bar

For anyone familiar with ASP.NET MVC or Django, this would be similar to route.MapRoute in the former and using (? P \ d +) in urlpatterns in the latter.

It would be possible to process the data in the Http request object directly to get this, but I would like to know if Spring MVC has support for this (version 2.5 in particular).

+2


source to share


2 answers


No, Spring doesn't support this out of the box. However, you can specify the path to the method name using @RequestMapping and configured accordingly InternalPathMethodNameResolver

:

@Controller
@RequestMapping("/bar/*")
public class MyController {
  ...
  public String do99(HttpServletRequest request) {
    ...
  }
}

      



You need to specify prefix

for InternalPathMethodNameResolver

how to "make" to work above works because the method names can not start with a number. If you want to use "foo.com/bar/baz" as the URL and call your method baz

, no additional configuration is required.

If you don't want to use method name mapping, getting "99" as a parameter is as simple as capturing it from request.getPathInfo()

within your method.

0


source


For anyone using Spring 3, I found out that this can be done with the new @PathVairable annotation

Here is an example from http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/



@RequestMapping("/hotels/{hotelId}")
public String getHotel(@PathVariable String hotelId, Model model) {
    List<Hotel> hotels = hotelService.getHotels();
    model.addAttribute("hotels", hotels);
    return "hotels";
}

      

+12


source







All Articles