将动态输入字段绑定到bean类spring mvc

时间:2015-02-17 13:00:05

标签: java javascript spring spring-mvc web-applications

我有一个表单 - 我在表单中添加动态输入字段,如何将这些动态输入值绑定到bean类中的列表(Java.lang.Util)变量。

我的表格:

My Form with dynamic options

    public class CQuestion {    
    private String question;
    private List<COption> COptions;
    public CQuestion() {
    }
    public String getQuestion() {
        return this.question;
    }
    public void setQuestion(String question) {
        this.question = question;
    }
    public List<COption> getCOptions() {
        return this.COptions;
    }
    public void setCOptions(List<COption> COptions) {
        this.COptions = COptions;
    }
    public COption addCOption(COption COption) {
        getCOptions().add(COption);
        COption.setCQuestion(this);
        return COption;
    }
    public COption removeCOption(COption COption) {
        getCOptions().remove(COption);
        COption.setCQuestion(null);
        return COption;
    }
    }

COption.java bean类

public class COption {  

    private String option;  
    private String explanation; 
    private boolean isCorrect;

    public COption() {
    }   

    public String getOption() {
        return this.option;
    }

    public void setOption(String option) {
        this.option = option;
    }

    public boolean isCorrect() {
        return isCorrect;
    }

    public void setCorrect(boolean isCorrect) {
        this.isCorrect = isCorrect;
    }

    public String getExplanation() {
        return explanation;
    }

    public void setExplanation(String explanation) {
        this.explanation = explanation;
    }

}

我的控制器:

@RequestMapping(value = "/add", method = RequestMethod.POST, produces = { "application/json" })
public @ResponseBody String add(@ModelAttribute CQuestion question,
        BindingResult result, Model model) {
}

使用上面的代码,我只得到问题值而不是选项值(java.lang.util.List)。你能建议我用bean类绑定这些动态选项吗?

1 个答案:

答案 0 :(得分:0)

我假设你正在做ajax帖子。如果是这种情况,你可以做类似的事情。

var options= new Array();
options.push("option1"); // these are values from your dynamic fields
options.push("option2");
$.ajax({
        url: "/add",
        type: "POST",
        datatype: "json",
        data: {COptions:options},
        error: function (xmlHttpRequest, errorText, thrownError) {
            alert(xmlHttpRequest, errorText, thrownError);
        },
        success: function (data) {
            alert("success");
        }
    });