【发布时间】: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