[英]submitting forms with multiple commandName or Modellattribute
I wanna save a comment by submitting the form below: 我想通过提交以下表单保存评论:
<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>
in the simplest case the addNewComment() method gets called in the Controller, and everything is fine. 在最简单的情况下,将在Controller中调用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);
}
Everything is fine as long as I don't want to record which User made the Comment. 只要我不想记录哪个用户发表了评论,一切都很好。 However if the Comment class contains a field which is a User like this
但是,如果Comment类包含一个像User这样的字段
@Entity
@Table(name = "comments")
public class Comment {
// more fields...
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
//getters-setters
and I have a valid User object in the .jsp file like this: 并且我在.jsp文件中有一个有效的User对象,如下所示:
<c:if test="${!empty LOGGED_IN_USER}">
<spring:message code="label.welcome" /> ${LOGGED_IN_USER.userName}
</c:if>
How can I send NOT only the Comment, but the LOGGED_IN_USER as well by submitting the above mentioned form? 通过提交上述表格,我不仅可以发送评论,还可以发送LOGGED_IN_USER吗?
The "solution" below is not gonna work: (crashes with org.apache.jasper.JasperException) 下面的“解决方案”不起作用:(使用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>
I am assuming your logged in user must in the session right - if so you can simply set the user into your comment inside your controller - 我假设您的登录用户必须在会话中具有权限-如果是这样,您只需将用户设置为控制器内的注释即可-
comment.setUser(sessionUser)
Or you can set the sessionUser when presenting your comment object, if so you can simply do: 或者,您可以在显示注释对象时设置sessionUser,如果是这样,您可以简单地执行以下操作:
<form:hidden path="user"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.