mvc
Avoiding ambiguities when using @RequestMapping
I’ve recently been using the param attribute of the @RequestMapping annotation from Spring MVC.
Take the case of a search feature for a website. If a ‘refine’ parameter is present, the user should be shown a search form to refine their criteria. However if the refine parameter is not present the user is shown the search results for the query.
public class SearchController {
// Handles search?query=dog&refine=true
@RequestMapping(params="refine=true")
public void refine() { ... }
// Handles search?query=dog
@RequestMapping
public void search() { ... }
}
While this code will initially work, there is some ambiguity in the way the URLs are matched. The order in which the @RequestMapping mappings are defined in the class file is actually determining which method will be called. If we were to define the search() method first, then a request to search?query=dog&refine=true would satisfy the conditions for the search() method’s @RequestMapping and thus the params="refine=true" on the refine() method has no bearing on the outcome of the request.
To safeguard the controller against the potential reordering of methods in a class (which in usual Java programming has no affect on the outcome of running code), we need to ensure the parameter mapping is explicit.
@RequestMapping(params="refine=true")
public void refine() { ... }
// Match if 'refine' parameter is not present
@RequestMapping(params="!refine=true")
public void search() { ... }
By explicitly checking the refine parameter is not present for the search method’s request mapping (!refine=true), the declaration order of our @RequestMapping annotations in the class file has no bearing on which method handles the request thus making our code robust to the reordering methods. Similar precautions should be taken with the other attributes of @RequestMapping including method and headers.
Spring’s Dependency Injection & MVC
Below are slides from a presentation I gave to colleagues at Kiwiplan. The presentation covered two Spring Framework topics, the first being a brief introduction to Spring’s Dependency Injection Container. The second presentation was an introduction to Spring’s MVC (web) component, with a focus on the annotation style introduced in Spring 2.5. PDF versions are available for both Dependency Injection and MVC.
Search
Subscribe
Recent Posts
Tags
Archives
What I'm Doing...
- (2008..new Date()[Calendar.YEAR]).each() {} #lovingthegroovy 16 hrs ago
- Gotta love cheap local branches with Git 18 hrs ago
- Test List for VS2010 looks useful http://site.typemock.com/test-lint Anyone know of an equivalent for JUnit/Eclipse? /cc @robfe 1 day ago
- More updates...