Reputation: 125
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.
Upvotes: 6
Views: 4115
Reputation: 2505
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.
Upvotes: 7
Reputation: 68715
Create a class
, encapsulate all the attributes in that class and then accept that class object as your @ModelAttribute
. Something like:
public class MyData {
private String name;
private String description;
private String price;
private String company;
private String volume;
private String weight;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getVolume() {
return volume;
}
public void setVolume(String volume) {
this.volume = volume;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
}
And then modifying your addProduct method like this:
public String addProduct(@ModelAttribute MyData myData, ModelMap model)
Upvotes: 3