How can I avoid too many arguments in Spring Java controllor

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 / link the total number of arguments.

+4
source share
2 answers

create a form class ie

 class MyForm{ String name; String price; String description; ... // Getters and setters included } 

and you like

 @RequestMapping(value = NEW) public String addProduct(@ModelAttribute MyForm myForm) 

creating MyForm and binding query parameters to its properties and adding to ModelMap is done by spring behind the scenes.

Source: Spring Docs

An @ModelAttribute in the method argument indicates that the argument should be extracted from the model. If not in the model, the argument must first be instantiated and then added to the model. Once upon a time in the model, the argument fields should be filled out of all the query parameters with 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 separately.

+3
source

Create a class , encapsulate all the attributes in this class, and then accept this class object as @ModelAttribute . Sort of:

 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 change your addProduct method as follows:

 public String addProduct(@ModelAttribute MyData myData, ModelMap model) 
+3
source

Source: https://habr.com/ru/post/1495815/


All Articles