处理动态表单

Handling dynamic form

我正在尝试处理动态 spring 表单。关键是,在运行时之前我不知道到底有多少输入形式。我不知道可以与@RequestParam 一起使用的输入名称或任何类型的信息。

这是我的控制器:

@RequestMapping(value = "/surveys/{id}", method = RequestMethod.GET)
public String survey(@PathVariable int id, ModelMap model) {
    model.addAttribute("surveyForm", getQAForm(id));
    return "user/survey";
}

@RequestMapping(value = "/submitSurvey", method = RequestMethod.POST)
public String submitSurvey(@ModelAttribute("surveyForm") QAForm qaForm, ModelMap modelMap){
    Set<Answer> answers = qaForm.getAnswers();
    modelMap.addAttribute("answers", answers);
    return "test";
}

和jsp的:

       <f:form method="post" modelAttribute="surveyForm" action="/submitSurvey">>
        <h2>${surveyForm.survey.title}</h2>
        <h5>${surveyForm.survey.description}</h5>
        <c:forEach items="${surveyForm.answers}" var="answer">
          <div class="panel panel-default">
            <div class="panel-heading">
                ${answer.question.text}
            </div>
            <div class="panel-body">
              <f:input path="${answer.answerText}" type="text" />
            </div>
          </div>
        </c:forEach>
        <input class="btn btn-default" type="submit" value="Submit"/>
        <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
      </f:form>

在处理 /submitSurvey 请求后,它会简单地重定向到 test.jsp,而无需来自表单的任何信息。如果有任何方法可以用另一种方式处理这个问题,我将不胜感激,指出我正确的方向。

你可以这样做:

  @RequestMapping(value = "/surveys/{id}", method = RequestMethod.GET)
   public String survey(@PathVariable int id, ModelMap model,@RequestParam("description") String desc) {
   // here you can handl the param description
    model.addAttribute("surveyForm", getQAForm(id));
    return "user/survey";
 }

但是你应该在页面的表单中包含这个参数 jsp 比如:

  <f:form method="post" modelAttribute="surveyForm" action="/submitSurvey">>
<input type="text" name="description" />
 ....

目前还不清楚您到底在问什么,但是如果它是关于绑定集合的,您将需要进行以下更改。

  1. 答案需要存储在列表中,而不是集合中。即 qaForm.getAnswers() 必须 return 列表,因为 Spring 只能绑定到索引可访问的集合。

  2. 更改 JSP 标记以使用索引属性,如下所示:

.

<c:forEach items="${surveyForm.answers}" var="answer" varStatus="status">
        <div class="panel panel-default">
            <div class="panel-heading">
                ${answer.question.text}
            </div>
            <div class="panel-body">
              <f:input path="answer[${status.index}].answerText" type="text" />
            </div>
        </div>
</c:forEach>

要在提交时填充现有调查,请进行以下更改(根据 http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-modelattrib-method-args

  1. 在提交调查 ID 的表单中添加一个隐藏字段。

  2. 向您的控制器添加一个方法,如下所示,它将加载指定的调查并将提交的数据绑定到此现有实例。

.

@ModelAttribute("surveyForm")
public SurveyForm getSurveyForm(@RequestParam(required = false) Integer surveyId){
    if(id != null){ 
       //load the form required by id   
    }
}