【问题标题】:show username in html Spring Security在 html Spring Security 中显示用户名
【发布时间】:2017-07-31 19:59:00
【问题描述】:

我正在使用 Spring 安全配置,现在我想在 html 页面上显示用户名。 我获取用户名的方法:

@Controller
public class UserController {

    @RequestMapping(value = "/username", method = RequestMethod.GET)
    @ResponseBody  public String currentUserName() {
    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String name = user.getUsername();
        return name;
    }
}

所以导航 http://localhost:8080/username 显示正确的用户名

但是当我尝试在 html 上显示用户名(使用 GET 请求)时没有任何反应

这是我尝试做的:

<head>
<script>
function httpGet()
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", "http://localhost:8080/username", false );
    xmlHttp.send( null );
   document.getElementById('usr').innerHTML=xmlHttp.responseText;
}
window.onload=httpGet;
</script>

</head>

<div id="usr">
</div>

提前感谢您的帮助!

【问题讨论】:

  • 您也可以将签名currentUserName()更改为currentUserName(Principal principal)并返回principal.getName();
  • @zelenov 在没有上下文路径的情况下尝试xmlHttp.open( "GET", "/username", false )
  • 尝试在 javascript alert(xmlHttp.responseText) 中添加警报;

标签: javascript java html spring spring-security


【解决方案1】:

试试

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
        document.getElementById('usr').innerHTML=xhr.responseText;
    }
}
xhr.open("GET", "http://localhost:8080/username", true);
xhr.send(null);

还可以考虑使用 jQuery 之类的东西来执行请求,这样会更容易。 例如,您可以使用 Chrome 开发工具调试 js 代码。

【讨论】:

  • 非常感谢,但仍然没有显示任何内容
  • 我建议用 chrome 或 firefox 打开网页并打开开发工具。您可以检查是否有错误,甚至在 onreadystatechange 函数中放置一个断点
猜你喜欢
  • 2017-08-28
  • 2021-10-27
  • 2021-08-26
  • 2016-11-01
  • 2016-11-23
  • 2014-08-12
  • 2013-12-14
  • 2019-01-01
  • 2016-04-27
相关资源
最近更新 更多