简体   繁体   中英

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, eg:

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?

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

You can try @ModelAttribute and method=RequestMethod.POST: In your controller:

//...
@RequestMapping(value="/method", method=RequestMethod.POST)
public String add(@ModelAttribute("modelName") ModelClass form)
{
   //.. your code
}

//..

In your JSP:

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="f" %>

//.. some code 

<f:form action="method" method="post" modelAttribute="modelName">

</f:form>

If you are restricted to GET requests only, you might not be able to use a separate ModelClass. You need to resort to request parameters in that case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM