Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid having 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/bind total number of arguments.

like image 444
Prashant Avatar asked Feb 16 '23 15:02

Prashant


1 Answers

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.

like image 195
harrybvp Avatar answered Apr 06 '23 08:04

harrybvp