使用多个commandName或Modellattribute提交表单

时间:2012-08-20 09:17:33

标签: java spring hibernate form-submit

我想通过提交以下表单保存评论:

<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>

在最简单的情况下,在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);
    }

只要我不想记录哪个用户发表了评论,一切都很好。 但是,如果Comment类包含一个像这样的用户

的字段
@Entity
@Table(name = "comments")
public class Comment {

    // more fields...

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

   //getters-setters

我在.jsp文件中有一个有效的User对象,如下所示:

<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>

1 个答案:

答案 0 :(得分:0)

我假设您的登录用户必须在会话中 - 如果是这样,您只需将用户设置到控制器内的评论中即可 -

comment.setUser(sessionUser)

或者您可以在呈现评论对象时设置sessionUser,如果是这样,您可以执行以下操作:

<form:hidden path="user"/>