Customizing Parameter Names When Binding Spring MVC Command Objects

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;
}

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;
}