显示使用Spring,Spring Security,Hibernate,jQuery,Backbone,AJAX的We

Display the name of a current log-on user of web-app which uses Spring, Spring Security, Hibernate, jQuery, Backbone, AJAX

本文关键字:Spring Backbone AJAX We jQuery Security 显示 Hibernate      更新时间:2023-09-26
如何在

HTML 页面中显示当前用户的名称?不幸的是,我是Javascript/jQuery的新手。所以我在Spring MVC,Spring Security,Hibernate,jQuery,Backbone.js的帮助下创建了一个Java应用程序。我不使用 JSP 和 EL。我的应用程序是单页 AJAX 样式的。我的用户(=client)成功登录,控制器将他重定向到客户的个人页面,控制器的一个方法将用户的名称作为字符串返回给我。我应该如何使用它在页面中显示?

@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;
    }

任何帮助都非常感谢。

像这样:

/

/import 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";
}
您可以使用

<sec:authentication property="principal.username" /> .见 http://docs.spring.io/spring-security/site/docs/3.0.x/reference/taglibs.html

HTML

静态的,您无法将登录的用户名动态放入其中。将其更改为 jsp,上面的答案将帮助您显示登录的用户名。