<!DOCTYPE html> <head xmlns:th="http://www.w3.org/1999/xhtml" xmlns:th="http://www.w3.org/1999/xhtml"> <meta charset="UTF-8"> <title>java资源分享</title> <link rel=""> <script type="text/javascript" src="/js/jquery-3.3.1.js"></script> </head> <body>
//前端代码 <div> <li class="welcome"></li> </div>
<script type="text/javascript"> $(function(){ $.ajax({ url:"/User/getLogin_username", type:"post", success:function (data) { if(data == "error2"){ console.log("用户没有登录") } if(data != null && data != undefined && data !=="error2"){ $(".welcome")[0].innerHTML= data+ "欢迎你" } },error:function () { alert("用户没有登录") } }) }) </script>
</body> </html>
//后端代码,前提是用户已经登录才能获取用户名,并且在session中存入的值为user
@Controller @RequestMapping("/User") public class UserController { @ResponseBody @RequestMapping("/getLogin_username") public String getLogin_username(HttpSession session){ User user = (User) session.getAttribute("user"); if(user == null){ return "error2"; } String username = user.getUsername(); System.out.println(user); return username; }
}