javascript - 显示使用 Spring、Spring Security、Hibernate、jQuery、Backbone、AJAX 的 web-app 的当前登录用户的名称

标签 javascript jquery ajax spring backbone.js

如何在 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/

相关文章:

javascript函数等待另一个函数完成

php - 在 myphp 中添加项目

javascript - 循环遍历 JSON 并动态填充数据

javascript - 通过 AJAX 加载脚本标签

javascript - Kineticjs 将元素添加到舞台

javascript - 我如何使用 jQuery 获取 <img> 标签内的宽度

jquery - 使用 jquery 动态更改 css 图像

javascript - 永久保存jquery修改的页面

php - 有没有其他方法可以通过 PHP 将 mySQL 数据输出到 XML 中? (适用于 Google map API V3)

javascript - Dotnet 和 JavaScript url 编码