Steve Chambers Steve Chambers - 1 year ago 113
Java Question

How to ensure mandatory parameters are passed into a Spring MVC controller method?

Given a Spring-MVC controller method:

@RequestMapping(value = "/method")
public void method(@RequestParam int param1,
@RequestParam int param2) { /*...*/ }

If parameters are missing in the request URL, an error is reported, e.g:

JBWEB000068: message Required int parameter 'param1' is not present

I need to move the parameters into a single model class yet keep exactly the same GET request URL. So have modified
's parameter to
MyModel model
, which contains

This works if
is omitted but the snag is no error is reported if parameters are missing. If, on the other hand
is included, a parameter named "model" is expected in the GET request. Is there a way to make model parameters mandatory yet keep the same request URL?

Answer Source

Use JSR-303 annotations to validate the object (and don't use primitives but the Object representations in that case).

public class MyObject {
    private Integer param1;

    private Integer param2;

    // Getters / Setters


Controller method.

@RequestMapping(value = "/method")
public void method(@Valid MyObject obj) { /*...*/ }

If you don't have a JSR-303 provider (hibernate-validator for instance) on your classpath create a Validator and use this to validate your object.


  1. Spring MVC reference guide
  2. Spring Validation reference guide
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download