简体   繁体   English

Java-从数据库获取用户名

[英]Java - Get username from DB

I have a side-project website, where people can comment on stuff , now I need to display user's comments and the username of commenter. 我有一个辅助项目网站,人们可以在其中发表评论,现在我需要显示用户的评论和评论者的用户名。 The problem is that I can't get a username of logged in user. 问题是我无法获得已登录用户的用户名。

Comment Examples : 评论示例:

1) Commented By - Shelo 1) 评论者-Shelo
Test Comment 测试评论

2) Commented By - ProGa 2) 评论者-ProGa
Test Comment 2 测试评论2

Now, The problem is that If I try to get the "currently logged in" user's username, both comments will have same username when user logges in 现在,问题在于,如果我尝试获取“当前登录”用户的用户名,则用户登录时两个注释将具有相同的用户名。

Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
String name = loggedInUser.getName();

This code example above is how you get currently logged in user. 上面的代码示例是您当前如何登录用户的方式。 So If I use this code and try to display username by String name , and lets say some user logges in with username - "Davos" , both comments will look like this - : 因此,如果我使用此代码并尝试通过String name显示用户String name ,并假设某些用户使用用户名“ Davos”登录,则两个注释都将如下所示::

1) Commented By - Davos 1) 评论者-达沃斯
Test Comment 测试评论

2) Commented By - Davos 2) 评论者-达沃斯
Test Comment 2 测试评论2

What I need is - to get the username of a user who's logged in and if he leaves the comment , display his username. 我需要的是-获取登录用户的用户名,如果他留下评论,则显示其用户名。 When he logges out or some other user logges in , the "username" of the comment should stay same and must not change depending of who's currently logged in . 当他注销或其他一些用户登录时,注释的“用户名”应保持不变,并且不得根据当前登录的用户而更改。

My Database Schema 我的数据库架构

Controller Class (only relevant code): 控制器类(仅相关代码):

@GetMapping("/foodDescription/{id}")
public String foodDescriptionPage(Model model, @PathVariable(name = "id") String id){
    menuRepository.findById(id).ifPresent(o -> model.addAttribute("menu", o));


    return "food-description";
}

@PostMapping("/postComment/{id}")
public String postComment(@RequestParam String myComment, Model model, @PathVariable(name = "id") String id){

    Optional<Menu> menu = menuRepository.findById(id);
    menuRepository.findById(id).ifPresent(o -> model.addAttribute("menu", o));
    List<Comments> myCommentsList = menu.get().getComments();
    myCommentsList.add(new Comments(myComment));

    menu.get().setComments(myCommentsList);
    menuRepository.save(menu.get());

    return "food-description";
}

food-description.html (Only relevant code for comments section) : food-description.html(仅有关注释的代码部分):

    <h3 th:text = "Comments">asd</h3>
<form th:action = "@{/postComment/{myMenuId}(myMenuId=${menu.id})}" method="POST">
    <textarea rows="2" cols="100" name="myComment"></textarea>
    <input type="submit" th:value="Add"/>
</form>

<div class="comment" th:each="com : ${menu.comments}">
    <h3 th:text="Display Commenter's Username here">Commenter's Username</h3>
    <ul>
        <li th:text = "${com.comment}">Comment</li>
    </ul>
</div>

User entity : 用户实体:

@Entity
@Table(name = "users")
public class User {

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

    @Column(name = "username")
    private String userName;

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

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

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

    @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinTable(name = "users_role",
    joinColumns = @JoinColumn(name = "user_id"),
    inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Role role;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinTable(name = "users_comments",
    joinColumns = @JoinColumn(name = "user_id"),
    inverseJoinColumns = @JoinColumn(name = "comment_id"))
    private List<Comments> comments = new ArrayList<>();

    // Getters/Setters/Constructor

} }

Comment entity : 评论实体:

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

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

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

    // Getters/Setters/Constructor

As mentioned in the comments, you have to change your data modeling. 如评论中所述,您必须更改数据建模。

For example you can implement something like this: 例如,您可以实现以下内容:

@Entity
public class User {
   @OneToMany()
   public Collection<Comment> comments;
   ...
}

@Entity
public class Comment {
   @ManyToOne
   @JoinColumn(name="user_fk")
   public User user;
   ...
}

In this case you have a bidirectional association and you are able to obtain the user form a comment in code (and in the html template). 在这种情况下,您具有双向关联,并且可以通过代码(和html模板)中的注释获得用户。 Of course you have to change your DB model too, if you are doing it manually. 当然,如果您手动进行操作,则还必须更改数据库模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM