Saturday, 9 July 2011

Accessing Path Variables in Spring MVC

One of the neat things you can do in Spring 3 MVC is to map pieces of a URL request string into specific controller method input arguments. This is done by using a mixture of two annotations: @RequestMapping and @PathVariable. As mentioned in a previous blog, the @RequestMapping annotation is used to filter and route browser requests to specific methods using its arguments: value, method, params and headers.

To extract part of the request string, you first need to specify a variable name and surround it with ‘{‘ and ‘}’ characters: for example {myVariable}. You then substitute this into the @RequestMapping annotation as part of the value attribute:

  @RequestMapping(value = "/help/{myVariable}", method = RequestMethod.GET)

To complete the task, add the @PathVariable annotation to your controller method signature

  @RequestMapping(value = "/help/{myVariable}", method = RequestMethod.GET)
 
public String displayHelpDetail(@PathVariable String myVariable, Model model) {

   
etc...

 
}

Using the method signature above will route any GET request starting with /help to the method. For example, it will route both /help/hello and /help/world to the displayHelpDetail sticking the values hello and world into the myVariable variable on each occasion.

1 comment:

Adam Perry said...

Nice post!

A neat little extra is that if you add the @RequestMapping to the class, rather than the method, you can still access path variables.

e.g.

@RequestMapping("/help/{myVariable}")
class MyClass {

public String displayHelpDetail(@PathVariable("myVariable") myVariable) { ... }

}