如何在 HTML 页面中显示当前用户的名称?不幸的是,我是 Javascript/jQuery 的新手。 因此,我在 Spring MVC、Spring Security、Hibernate、jQuery、Backbone.js 的帮助下创建了一个 Java 应用程序。 我不使用 JSP 和 EL。 我的应用程序是单页 AJAX 样式的。我的用户(=客户端)成功登录, Controller 将他重定向到客户端的个人页面, Controller 的一种方法将用户名作为字符串返回给我。我应该如何使用它才能显示在页面中?
@RequestMapping(value = "/client", method = RequestMethod.GET)
public String client(Locale locale, Model model, ModelMap modelMap, Principal principal) {
String currentUser = getActiveUser(modelMap, principal);
System.out.println("Current user is " + currentUser);
/*The username of the current user is written in the
Eclipse console successfully*/
return "forward:/pages/client.html";
}
public String getActiveUser(ModelMap modelMap, Principal principal) {
String name = principal.getName();
modelMap.addAttribute("userName", name);
return name;
}
非常感谢任何帮助。
最佳答案
像这样:
//导入org.springframework.security.core.userdetails.User;
@RequestMapping(value="/login", method = RequestMethod.GET)
public String printUser(ModelMap model) {
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = user.getUsername(); //get logged in username
model.addAttribute("username", name);
return "homepage";
}
(或)
@RequestMapping(value="/login", method = RequestMethod.GET)
public String printUser(ModelMap model) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName(); //get logged in username
model.addAttribute("username", name);
return "homepage";
}
关于javascript - 显示使用 Spring、Spring Security、Hibernate、jQuery、Backbone、AJAX 的 web-app 的当前登录用户的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19680363/