在利用springboot进行web开发时,遇到这样一个问题:html如何获取session中的值,实现用户登录系统后首页展示xx欢迎您。
也就是需要实现html通过ajax请求获取session中的值。
1.登录页面
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<meta charset="utf-8">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>测试</title>
</head>
<body>
<form action="../checkuser" method="post">
<table>
<tr>
<td> 姓名:</td>
<td width="25">
<input type="text" name="username" value="">
</td>
</tr>
<tr>
<td> 密码:</td>
<td width="25">
<input type="text" name="password" value="">
</td>
</tr>
</table>
<button type="submit" >提交</button>
</form>
</body>
</html>
2.处理用户登录请求的controller
@Controller
public class TestController {
//控制器调用service层服务层
@Autowired
private CheckUserService checkUserService;
//用户登录
@RequestMapping(value = "/checkuser")
public String checkUser(HttpServletRequest request, HttpServletResponse response, User user) throws Exception{
String username=user.getUsername();
String password=user.getPassword();
int user1=checkUserService.select(username,password);
if(user1==1){
System.out.println("登录成功!");
//将用户信息存放到session中
request.getSession().setAttribute("user",user);
return "redirect:main";
}else{
System.out.println("登录失败!");
return "redirect:toindex";
}
}
@RequestMapping(value = "/main")
public String toIndex(){
return "user/addUser";
}
@RequestMapping(value = "/toindex")
public String toError(){
return "error/error";
}
}
3.登录成功后进入首页
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="../js/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
//当页面一加载时就向后台发送post请求
$(function(){
$.post("../username/getusername",function(obj){
$("#roleName").html(obj.username+"欢迎你");
},"json")
});
</script>
</head>
<body>
需要使用ajax请求,页面加载完成就向后台发送请求<br>
<span id="roleName">xxx</span><br>
</body>
</html>
4.处理页面加载时controller
@Controller
@RequestMapping("username")
public class IndexController {
@RequestMapping(value = "/getusername")
public void getUsername(HttpServletRequest request, HttpServletResponse response)throws Exception{
//先从session中获取到之前存在session中的用户信息,然后通过ObjectMapper输出返回一个json数据给html页面,由页面去解析这个json数据
User user=(User)request.getSession().getAttribute("user");
if(user!=null){
ObjectMapper objectMapper=new ObjectMapper();
objectMapper.writeValue(response.getOutputStream(),user);
}
}
}
以上就是html通过ajax请求获得session中的值的全过程。