如何避免在Spring Java控制器中包含太多参数

时间:2013-08-07 18:43:08

标签: java spring-mvc parameters controller parameter-passing

在我的Spring网络应用程序中:

    @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;
    }
}

减少/绑定参数总数的可能方法有哪些。

2 个答案:

答案 0 :(得分:3)

创建class,封装该类中的所有属性,然后将该类对象作为@ModelAttribute接受。类似的东西:

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;
    }

}

然后像这样修改你的addProduct方法:

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

答案 1 :(得分:3)

创建表单类,即

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

并且喜欢

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

MyForm的实例化以及请求参数与其属性的绑定以及添加到ModelMap的操作都是在幕后进行的。

来源:Spring Docs

  

方法参数上的@ModelAttribute指示参数应该   从模型中检索。如果模型中没有,则参数   应首先实例化,然后添加到模型中。一旦到场   在模型中,参数的字段应该从所有字段中填充   请求具有匹配名称的参数。这称为数据   Spring MVC中的绑定,一种非常有用的机制,可以帮助您避免使用   必须单独解析每个表单字段。