你能告诉我如何以最方便的方式将多个参数从 View 传递到 Controller 的函数吗?
JSP View :
<h2>${topic.getName()}</h2>
<h3>${topic.getText()}</h2>
<form:form method="post" commandName="newComment">
<fieldset>
<div class="editor-label">
<td><form:label path="text">Input comment</form:label></td>
</div>
<div class="textarea">
<form:textarea path="text" />
</div>
<p>
<input type="submit" value="Comment" />
</p>
</fieldset>
</form:form>
如您所见,我们有 topic 和 newComment 属性,它们代表主题和评论实体。
这是一个 Controller :
@RequestMapping(value = "/addComment/{topicId}", method = RequestMethod.POST)
public String saveComment(@ModelAttribute("newComment")Comment comment, BindingResult result, Model model){
validate(comment, result);
if (result.hasErrors() )
{
return "//";
}
return "redirect:details/";
}
}
评论实体可以很好地识别,但我还需要一个 Topic 对象的实例(或其 ID)。主题对象的实例可以在 View 中访问,主题 ID 是响应的一部分。你能给我一个想法,我该如何处理这个问题吗?
最佳答案
有了topicId
就能得到主题模型吗?它就在你的路上。
您可以通过在方法参数中添加 @PathVariable
注解来获取它。
public String saveComment(@PathVariable String topicId, @ModelAttribute("newComment")Comment comment, BindingResult result, Model model){
关于java - 如何将多个参数从 View 传递到 Controller 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11940470/