我想通过提交以下表格来保存评论:
<form:form method="post" action="postNewComment.html" commandName="comment" >
<table>
<tr>
<td><form:label path="comment">
COMMENT
</form:label></td>
<td><form:input path="comment" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit"
value="WRITE" /></td>
</tr>
</table>
</form:form>
在最简单的情况下,在控制器中调用 addNewComment() 方法,一切都很好。
@RequestMapping(value = "/postNewComment", method = RequestMethod.POST)
public ModelAndView addNewComment(@ModelAttribute("comment") Comment comment, BindingResult result) {
commentService.addComment(comment);
Map<String, Object> model = new HashMap<String, Object>();
model.put("COMMENTS", commentService.getComments());
return new ModelAndView("showAllComments", model);
}
只要我不想记录哪个用户发表了评论,一切都很好。 但是,如果 Comment 类包含一个像这样的 User 字段
@Entity
@Table(name = "comments")
public class Comment {
// more fields...
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
//getters-setters
我在 .jsp 文件中有一个有效的用户对象,如下所示:
<c:if test="${!empty LOGGED_IN_USER}">
<spring:message code="label.welcome" /> ${LOGGED_IN_USER.userName}
</c:if>
如何通过提交上述表格不仅发送评论,还发送 LOGGED_IN_USER?
下面的“解决方案”不起作用:(与 org.apache.jasper.JasperException 崩溃)
<form:form method="post" action="postNewComment.html" commandName="comment" >
<table>
<tr>
<td><form:label path="comment">
COMMENT
</form:label></td>
<td><form:input path="comment" /></td>
</tr>
<tr>
<td><form:label path="user">
USER
</form:label></td>
<td><form:input path=" ${LOGGED_IN_USER}" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit"
value="WRITE" /></td>
</tr>
</table>
</form:form>