session在web项目中不可或缺,下面记录session的用法
以登录为例:
登录成功后我会在session中写入用户名和id
loginAction中的代码
ServletActionContext.getRequest().getSession().setAttribute("userName", txtUserName);//把值存入session
ServletActionContext.getRequest().getSession().setAttribute("userId", users.get(0).getId());//把值存入session
前台jsp页面获取的方法如下:
<%
String path = request.getContextPath();String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
String sessionValues=(String)request.getSession().getAttribute("userName");
String idSessionValues=(String)request.getSession().getAttribute("userId");
%>
js中判断用户名是否登录
if("<%=sessionValues%>"=='null'){
showLogin();
bingLogin();
}else{
hiddenLogin();
}
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
String sessionValues=(String)request.getSession().getAttribute("userName");
String idSessionValues=(String)request.getSession().getAttribute("userId");
%>
if("<%=sessionValues%>"=='null'){
showLogin();
bingLogin();
}else{
hiddenLogin();
}
ps:前台页面获取session,因为session是服务端的变量。jsp页面是客户端。所以每次页面需要刷新才能更新session。 而且在 jsp中 也是不能给java变量 sessionValues和idSessionValues赋值的。
如果需要实现无更新登录,只能用过action把登录用户id传值过来 赋值给一个前台页面变量,我们检查用户登录时也只能用一个前台变量 var userid。 实现假登录。 等用户刷新页面后,就会变成真登录了。