【问题标题】:How to get logged User_Id in Spring MVC如何在 Spring MVC 中获取记录的 User_Id
【发布时间】:2017-03-13 17:29:54
【问题描述】:

我正在尝试在 Spring MVC 中获取记录的用户名和 ID。 我可以轻松获取登录的用户名,但无法获取 user_id。 我正在使用这段代码来获取用户/主体详细信息。

SecurityContextHolder.getContext().getAuthentication().getPrincipal();

如果有人知道如何获取记录的 user_id?

【问题讨论】:

  • 是你的内部ID吗?
  • @bart.s 保存的用户ID。但是当用户登录时,我想得到它的 ID,就像我能得到它的名字一样。
  • Spring security 将生成一个包含用户名的“org.springframework.security.core.userdetails.UserDetails”实例。如果您想访问您的用户模式,您将需要实现您自己的 UserDetails 子类并在您登录后立即填充它。请提供有关您如何实施登录的更多详细信息,以提供更好的建议。

标签: mysql spring spring-mvc


【解决方案1】:

实现org.springframework.security.core.userdetails.UserDetails 在您的 User 类中,请参见下面的示例。

@Entity  
@Table(name="users")
public class User implements UserDetails,Serializable{
      @Id
      @GeneratedValue
      @Column(name = "userId")
      private long userId;
}

然后使用以下代码获取用户详细信息。

User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

【讨论】:

    猜你喜欢
    • 2016-09-30
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 2017-09-07
    • 2021-08-17
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    相关资源
    最近更新 更多