In my Spring web application:
@RequestMapping(value = NEW)
public String addProduct(@RequestParam String name, @RequestParam(required = false) String description,
@RequestParam String price, @RequestParam String company, ModelMap model,
@RequestParam(required = false) String volume, @RequestParam(required = false) String weight) {
try {
productManagementService.addNewProduct(name, description, company, price, volume, weight);
model.addAttribute("confirm", PRODUCT_ADDED);
return FORM_PAGE;
} catch (NumberFormatException e) {
logger.log(Level.SEVERE, INVALID_VALUE);
model.addAttribute("error", INVALID_VALUE);
return FORM_PAGE;
} catch (InvalidUserInputException e) {
logger.log(Level.SEVERE, e.getMessage());
model.addAttribute("error", e.getMessage());
return FORM_PAGE;
}
}
What are the possible ways to reduce/bind total number of arguments.
create Form Class i.e
class MyForm{
String name;
String price;
String description;
...
// Getters and setters included
}
and do like
@RequestMapping(value = NEW)
public String addProduct(@ModelAttribute MyForm myForm)
instantiation of MyForm
and binding of request parameters to its properties and adding to ModelMap is done by spring behind the scenes.
Source: Spring Docs
An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. If not present in the model, the argument should be instantiated first and then added to the model. Once present in the model, the argument's fields should be populated from all request parameters that have matching names. This is known as data binding in Spring MVC, a very useful mechanism that saves you from having to parse each form field individually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With