Senior Java developer, one of the top stackoverflow users, fluent with Java and Java technology stacks - Spring, JPA, JavaEE. Founder and creator of http://computoser.com and http://welshare.com . Worked on Ericsson projects, Bulgarian e-government projects and large scale recruitment platforms. Member of the jury of the International Olympiad in Linguistics and the Program committee of the North American Computational Linguistics Olympiad. Bozhidar is a DZone MVB and is not an employee of DZone and has posted 82 posts at DZone. You can read more from them at their website. View Full User Profile

Customizing Parameter Names When Binding Spring MVC Command Objects

02.10.2012
| 4326 views |
  • submit to reddit

In spring MVC you can have

public class Job {
    private String jobType;
    private String location;
}

@RequestMapping("/foo")
public Strnig doSomethingWithJob(Job job) {
   ...
}

But that means “jobType” and “location” are the http parameter names, and there is no way to customize that. Which is odd, since this is meta-data, and it should be configurable by annotations.

But if you need to customize them (for example, for SEO reasons), you can plug some little pieces of code and Spring MVC will let you do it. Here is my solution to the problem. It makes use of the pluggable argument-resolution mechanism. So, I add my own resolver, see if a command object is annotated with a custom annotation, and if it is – apply the @CommanParameter mapping. Note that Rossen Stoyanchev, main spring-mvc developer also suggested a solution, and while it’s a better one (less code duplication), it won’t work with <mvc:annotation-driven />. Mine works with that (thanks to the post-processor)

In the end you can have:

@SupportsCustomizedBinding
public class Job {
    @CommandParameter("jt")
    private String jobType;
    @CommandParameter("loc")
    private String location;
}

From http://techblog.bozho.net/?p=779

 

Published at DZone with permission of Bozhidar Bozhanov, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: