我正在创建一个基本的 Spring Web 应用程序,其中涉及用户登录并进入其个人仪表板。当通过 Controller 实例化“登录”url 时,我使用了默认的 Spring Security 登录表单。我想知道的是,如何从数据库中检索刚刚登录的用户个人帐户信息? 这是实例化登录 URL 时 Controller 类中的内容
@RequestMapping("dashboard")
public String goDashboard(Model model){
model.addAttribute("user", new User());
return "dashboard"; // this is just returning the viewResolver JSP page
}
我假设上面的内容是不正确的,因为我个人认为创建一个新对象是错误的并且会给我空值。当我登录并尝试使用: <c:out value="${user.username}" />
显示时没有显示任何内容。
最佳答案
或者您可以将其放入 Controller 中:
@RequestMapping("dashboard")
public String goDashboard(Model model, Principal principal){
model.addAttribute("username", principal.getName());
return "dashboard";
}
这种方法将帮助您将业务逻辑保留在 Controller 中(关注点分离)。
编辑。传递用户详细信息对象:
@RequestMapping("dashboard")
public String goDashboard(Model model, Principal principal){
UserDetails userDetails = (UserDetails)((Authentication)principal).getPrincipal()
model.addAttribute("userDetails", userDetails);
return "dashboard";
}
关于java - Spring登录用户信息检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18764221/