当前位置: 动力学知识库 > 问答 > 编程问答 >

forms - The foreach tag in JSP and how to write the code in the Java controller

问题描述:

I have one controller (RegisteredController.java) , and I want that the output of the controller is displayed in the JSP (its name is commment_form.jsp). So I use a forEach tag in the jsp to display a list of comments (the comments which the user has inserted about a given resource). For "resource" I usually mean an image. So there are a list of comments about an "image" and I want that all the comments are all displayed in the bottom page, when a comment is going to be inserted into the comment form. My question is how must be written the code into the controller in order to set the output for the jsp ? Should I use a @ModelAttribute , a put-attribute or something else ? Here is the code of the controller and of the jsp :

The comment_form.jsp is:

<form:form modelAttribute="comments">

<table class="commento">

<tr>

<th/>

<th>ID</th>

<th>Contenuto</th>

</tr>

<c:forEach items = "${comments}" var="comment">

<tr>

<td><c:out value="${comments.content}"></c:out></td>

<td><c:out value="${comments.content}</c:out></td>

</c:forEach>

</table>

</form:form>

The RegisteredController.java is:

 @RequestMapping("/comment.do")

public String comment(@ModelAttribute Comment comment, BindingResult

bindingResult, Model model, Locale locale) {

User user=userService.getUserCurrent();

comment.setDatePubblication(SQLUtility.getCurrentDate());

comment.setIdUser(user.getId());

commentService.create(comment);

Object[] args = { comment.getId() };

String message = messageSource.getMessage("message.update", args,locale);

List<Comment> comments =

commentService.findAllCommentByResource(comment.getIdResource());

model.addAttribute("comments", comments);

model.addAttribute("id",comment.getIdResource());

model.addAttribute("message", message);

model.addAttribute("comment", comment);

return "redirect:/registered/comment_start.do";

}

Please any help ? I will appreciate . Thanks you.

网友答案:

In case of redirect pass additional data as redirect attributes.

To carry data across a redirect use RedirectAttributes#addFlashAttribute(key, value).

What Java doc says:

A RedirectAttributes model is empty when the method is called and is never used unless the method returns a redirect view name or a RedirectView.

After the redirect, flash attributes are automatically added to the model of the controller that serves the target URL.

Read more...


One extra note :

In JSP it should be ${comment.content} instead of ${comments.content}

分享给朋友:
您可能感兴趣的文章:
随机阅读: