Steve Chambers Steve Chambers - 1 month ago 6
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
method
's parameter to
MyModel model
, which contains
param1
and
param2
.

This works if
@RequestParam
is omitted but the snag is no error is reported if parameters are missing. If, on the other hand
@RequestParam
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

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

public class MyObject {
    @NotNull
    private Integer param1;

    @NotNull
    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.

Links.

  1. Spring MVC reference guide
  2. Spring Validation reference guide