如何使用Spring在jstl中显示相关对象? [英] How to show related objects in a jstl using a spring?

查看:68
本文介绍了如何使用Spring在jstl中显示相关对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个对象:User,Comment和StatusUpdate(news).这是用户...

I have 3 objects: User, Comment and StatusUpdate(news). This is the User...

@Entity
@Table(name = "users")
@PasswordMatch(message = "{register.repeatpassword.mismatch}")
public class SiteUser {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;

@Column(name = "email", unique = true)
@Email(message = "{register.email.invalid}")
@NotBlank(message = "{register.email.invalid}")
private String email;

@Transient
@Size(min = 5, max = 15, message = "{register.password.size}")
private String plainPassword;

@Column(name = "password", length = 60)
private String password;

@Column(name = "enabled")
private Boolean enabled = false;

@NotNull
@Column(name = "firstname", length = 20)
@Size(min = 2, max = 20, message = "{register.firstname.size}")
private String firstname;

@NotNull
@Column(name = "surname", length = 25)
@Size(min = 2, max = 25, message = "{register.surname.size}")
private String surname;

@Transient
private String repeatPassword;

@Column(name = "role", length = 20)
private String role;

public SiteUser() {

}

这里是StatusUpdate(您可以称其为新闻或文章).该网站的用户就是创建该文章的用户.

Here comes the StatusUpdate(you can call it piece of news or article). That has a site user that is the one who has created that article.

@Entity
@Table(name = "status_update")
public class StatusUpdate {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Size(min=5, max=255, message="{addstatus.title.size}")
@Column(name = "title")
private String title;

@Size(min=5, max=5000, message="{addstatus.text.size}")
@Column(name = "text")
private String text;

@Column(name = "added")
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern="yyyy/MM/dd hh:mm:ss")
private Date added;

@OneToOne(targetEntity = SiteUser.class)
@JoinColumn(name="user_id")
private SiteUser siteUser;

@PrePersist
protected void onCreate() {
    if (added == null) {
        added = new Date();
    }
}

public StatusUpdate() {

}

任何注册用户都可以进行评论,对不对?您会注意到Comment没有User对象,以避免循环引用.

And the Comment which can be done by any registered user, right? As you will notice the Comment has no User object to avoid circular references.

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

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToOne
@JoinColumn(name = "statusupdateid")
private StatusUpdate statusUpdate;

@Column(name = "commenttext")
private String commenttext;

@Column(name = "commentdate")
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(pattern = "yyyy/MM/dd hh:mm:ss")
private Date commentdate;

@Column(name = "userid")
private Long userid;


public Comment() {
}

现在,我想在JSP中显示一篇文章,其中包含所有相关注释,并且每个注释都属于不同的用户.我可以使用HashMap关联用户及其评论吗?我不知道如何.

Now I would like to show in my JSP an article, with all the related comments and each of them belong to a different user. Can I use a HashMap to relate the users and their comments? I do not see how.

@RequestMapping(value ="/viewonestatus/{id}")
public ModelAndView viewOneStatus(@PathVariable("id") Long id) {

    StatusUpdate status = statusUpdateService.get(id);

    int countComments = commentService.countStatusComments(status);

    List<Comment> comments = commentService.readAllComments(status);

    ModelAndView modelAndView = new ModelAndView();

    for (Comment comment: comments){

        SiteUser user = userService.get(comment.getUserid());

        modelAndView.getModel().put("user", user);

    }

    modelAndView.getModel().put("commentscounter", countComments);
    modelAndView.getModel().put("status", status);
    modelAndView.getModel().put("comments", comments); //!!

    modelAndView.setViewName("app.viewonestatus");

    return modelAndView;
}

如您所料,当我的JSP对所有注释仅显示一个用户(最后一个)时,但是我无法将所有注释与相应的用户相关联

As you expect, when my JSP shows just one user (the last one) for all the comments, but I can not relate all the Comments with the corresponding Users

<table class="table table-hover">
    <c:forEach var="comment" items="${comments}">
    <tr>
        <td>

    <div class="col-sm-2 sm-margin-bottom-40">
        <img class="img-responsive profile-img margin-bottom-20" id="profilePhotoImage" src="/profilephoto/${comment.userid}" />
    </div>
                                                <h4> 
            ${user.firstname} ${user.surname} 
            <span> 
              <!--  <span>${counterUserMap[comment.key]}</span> -->
            5 hours ago / <a href="#">Reply</a>
            </span>
        </h4>
        <p>
            <fmt:formatDate pattern="EEEE d MMMM y 'at' H:mm:ss" value="${comment.commentdate}" />
        </p>
        <p>${comment.commenttext}</p>
    </td>
</tr>
</c:forEach>

我不想使用JSON.我正在考虑一个包含所有内容的匿名课程.好吧,我愿意接受您的想法.谢谢.

I do not want to use JSON. I'm thinking about an anonymous class with all the stuff inside. Well, I'm open to your thoughts. Thanks.

推荐答案

Shokulei的答案是解决方案:

Shokulei answer was the solution:

由于具有用户ID,因此可以使用@ManyToOne批注将其链接.这将是最理想的方法.但是,如果您真的不想链接它们,则可以创建一个新的@Transient SiteUser siteUser; Comment类中的属性.然后在for循环中,可以使用comment.setSiteUser(user);.而不是modelAndView.getModel().put("user",user);.希望这会有所帮助.

Since you have the userid, you can link it using the @ManyToOne annotation. This would be the most ideal way. But if you really don't want to link them, then you can create a new @Transient SiteUser siteUser; attribute in Comment class. And then in your for loop, you can use comment.setSiteUser(user); instead of modelAndView.getModel().put("user", user);. Hope this will help.

感谢Shokulei

Thanks Shokulei

这篇关于如何使用Spring在jstl中显示相关对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆