// 保存用户到session
req.getSession().setAttribute("sessionUser", user);
// 获取用户名保存到cookie中
String loginname = user.getLoginname();
loginname = URLEncoder.encode(loginname, "utf-8");
Cookie cookie = new Cookie("loginname", loginname);
cookie.setMaxAge(60 * 60 * 24 * 10);//保存10天
resp.addCookie(cookie);
//退出功能:
req.getSession().invalidate(); //销毁Session
jsp中用js获取Cookie和Session:
<script type="text/javascript">
$(function() {/*Map<String(Cookie名称),Cookie(Cookie本身)>*/
// 获取cookie中的用户名
var loginname = window.decodeURI("${cookie.loginname.value}");
if("${requestScope.user.loginname}") {
loginname = "${requestScope.user.loginname}";
}
$("#loginname").val(loginname);
});
</script>
时间: 2024-10-21 16:50:13