Reputation: 39424
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?
Upvotes: 0
Views: 2782
Reputation: 1
add ( ,@BindingResult result) in your parameter to bind the errors to all parameter. And you can check if the error exist using result.hasErrors()
Upvotes: 0
Reputation: 307
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.
Upvotes: 0
Reputation: 124632
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.
Upvotes: 4