4

在我的 Spring Web 应用程序中:

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

减少/绑定参数总数的可能方法是什么。

4

2 回答 2

5

创建表单类,即

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

并且喜欢

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

请求参数的实例化MyForm和绑定到其属性以及添加到 ModelMap 是由 spring 在幕后完成的。

资料来源:Spring Docs

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

于 2013-08-07T18:46:51.850 回答
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) 
于 2013-08-07T18:44:17.160 回答