我第一次使用
spring mvc而且我正在尝试在jsp中显示和编辑一个结构.
我有一个类Snippet,它包含Sentence类型的对象列表:
public class Snippet {
private int id;
private List<Sentence> sentences;
// getters, setters, default constructor
}
public class Sentence {
private int id;
private int scale;
private String text;
// getters, setters, default constructor
}
在我的控制器中,我提供了一个新的代码片段进行编辑,当用户点击“保存”将其存储到我的数据库中,然后返回另一个.目前,片段的句子列表为空:
@RequestMapping("/snippet")
public ModelAndView getSnippet() {
return new ModelAndView("snippet", "snippet", snippetService.getSnippet());
}
@RequestMapping("/save")
public ModelAndView saveSnippet(@ModelAttribute Snippet snippet) {
if(snippet != null && snippet.getSentences() != null && !snippet.getSentences().isEmpty()) {
snippetService.updateSnippet(snippet);
}
return new ModelAndView("snippet", "snippet", snippetService.getSnippet());
}
在我的snippet.jsp中,我想用它们的比例显示片段句子,并在保存时,将带有句子和缩放的片段传递给控制器进行存储:
<form:form method="post" action="save" modelAttribute="snippet">
...
<c:forEach var="sentence" items="${snippet.sentences}">
<tr>
<td>${sentence.id}</td>
<td>${sentence.text}</td>
<td><input type="range" name="sentence.scale" value="${sentence.scale}"
path="sentence.scale" min="0" max="5" /></td>
</tr>
</c:forEach>
<tr>
<td colspan="4"><input type="submit" value="Save" /></td>
</tr>
我想我必须找到使用path属性的正确方法,但我无法弄明白.
最佳答案 JSTL c:forEach标记提供属性varStatus,它将循环状态公开给指定的变量.引用varStatus的索引以获取当前循环的索引,并使用该索引指定要绑定或显示的集合项的索引.
<c:forEach var="sentence" items="${snippet.sentences}" varStatus="i">
<tr>
<td>${sentence.id}</td>
<td>${sentence.text}</td>
<td>
<form:input type="range"
name="snippet.sentences[${i.index}].scale"
path="sentences[${i.index}].scale"
min="0" max="5"
/></td>
</tr>
</c:forEach>