Javascript 在html Spring安全中显示用户名
我有工作的Spring安全配置,现在我想在html页面上显示用户名。 获取用户名的我的方法:Javascript 在html Spring安全中显示用户名,javascript,java,html,spring,spring-security,Javascript,Java,Html,Spring,Spring Security,我有工作的Spring安全配置,现在我想在html页面上显示用户名。 获取用户名的我的方法: @Controller public class UserController { @RequestMapping(value = "/username", method = RequestMethod.GET) @ResponseBody public String currentUserName() { User user = (User) SecurityContext
@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;
}
}
所以导航显示了正确的用户名
但当我尝试在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>
函数httpGet()
{
var xmlHttp=new XMLHttpRequest();
open(“GET”http://localhost:8080/username“,假);
xmlHttp.send(空);
document.getElementById('usr').innerHTML=xmlHttp.responseText;
}
window.onload=httpGet;
提前感谢您的帮助 试试看
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函数中放置一个断点,以便将签名
currentUserName()
更改为currentUserName(Principal Principal)
并返回Principal.getName()
@zelenov tryxmlHttp.open(“GET”,“/username”,false)
不使用上下文路径尝试在javascript警报(xmlHttp.responseText)中添加警报;