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

Try Okta to add social login, MFA, and OpenID Connect support to your Java app in minutes. Create a free developer account today and never build auth again.

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

 

Build and launch faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}