如何發佈數據和處理的ModelAttribute在這種情況下
你可以做結合,
我正在考慮Question
類,如:
public class Question {
private String question;
private Map<Integer,Option> optionMap;
private Integer selectedOptionKey;
//getters and setters
}
和Option
類,如:
public class Option {
private Integer optionKey;
private String optionText;
//getters and setters
}
和一個QuestionsModel
類形式樣結合:
public class QuestionsModel {
private Map<Integer, Question> questionMap;
//getters and setters
}
和內部控制類GET
處理方法,填充例如問題:
@RequestMapping(method=RequestMethod.GET)
public String index(Model model){
Option optionA = new Option(1, "A");
Option optionB = new Option(2, "B");
Option optionC = new Option(3, "C");
Map<Integer, Option> optionMap = new HashMap<Integer, Option>();
optionMap.put(optionA.getOptionKey(),optionA);
optionMap.put(optionB.getOptionKey(),optionB);
optionMap.put(optionC.getOptionKey(),optionC);
Question question1 = new Question("A Q", optionMap, 1);
Question question2 = new Question("B Q", optionMap, 1);
Question question3 = new Question("C Q", optionMap, 1);
Map<Integer, Question> questionMap = new HashMap<Integer, Question>();
questionMap.put(1, question1);
questionMap.put(2, question2);
questionMap.put(3, question3);
model.addAttribute("questionsModel", new QuestionsModel(questionMap));
return "index";
}
終於在JSP頁面中使用<form:hidden..
保留舊值,並渲染表單元素:
<c:url value="/questionPost" var="postUrl"/>
<form:form action="${postUrl}" modelAttribute="questionsModel" method="post">
<table>
<tr>
<th>Question</th>
<th>Options</th>
</tr>
<c:forEach items="${questionsModel.questionMap}" var="currQue" varStatus="queIndex">
<tr>
<td>
<form:hidden path="questionMap[${queIndex.count}].question"/>
<label>Question:</label><c:out value="${currQue.value.question}"/><br/>
</td>
<td>
<c:forEach items="${currQue.value.optionMap}" var="opt" varStatus="optionIndex">
<form:hidden path="questionMap[${queIndex.count}].optionMap[${optionIndex.count}].optionText"/>
<form:hidden path="questionMap[${queIndex.count}].optionMap[${optionIndex.count}].optionKey"/>
<form:radiobutton path="questionMap[${queIndex.count}].selectedOptionKey"
value="${opt.value.optionKey}" label="${opt.value.optionText}"/>
</c:forEach>
</td>
</tr>
</c:forEach>
</table>
<input type="submit"/>
</form:form>
即可領取綁定和模型POST,如:
@RequestMapping(value="/questionPost", method=RequestMethod.POST)
public String indexPost(@ModelAttribute("questionsModel") QuestionsModel questionModel, BindingResult result){
System.out.println(questionModel.getQuestionMap());
return "redirect:/";
}
[AutoPopulatingList](http://docs.spring.io/spring/docs/3.0。x/api/org/springframework/util/AutoPopulatingList.html) – GriffeyDog
我只想爲Question創建一個POJO類,而我的模型屬性將是這些Question對象的一個簡單列表,簡單且易於處理---- myList (或者,如果你只是需要問題文本和答案,你可以使用數組或地圖列表) –