Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Customizing Parameter Names When Binding Spring MVC Command Objects

DZone's Guide to

Customizing Parameter Names When Binding Spring MVC Command Objects

· Java Zone ·
Free Resource

The CMS developers love. Open Source, API-first and Enterprise-grade. Try BloomReach CMS for free.

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

 

BloomReach CMS: the API-first CMS of the future. Open-source & enterprise-grade. - As a Java developer, you will feel at home using Maven builds and your favorite IDE (e.g. Eclipse or IntelliJ) and continuous integration server (e.g. Jenkins). Manage your Java objects using Spring Framework, write your templates in JSP or Freemarker. Try for free.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}