服务器设置session后,前台获取代码的方法有3种:
第一种是直接用el表达式,
第二种是用JSP表达式。
第三种是网上说的,用jquerySession取值。但是测试中无法取到,我的判断是,jquery无法直接通过服务器获取session,需要服务器先将session传到客户端前台,然后jquerySession才能取值。
——————————————————————————————————————————————————————————————-
至于在客户端前台中 直接保存session是不允许的,需要通过服务器操作。
——————————————————————————————————————————————————————————————-
controller中代码
@RequestMapping(value = "/demo")
public String Demo(HttpSession session){
session.setAttribute("adminAccount","username=admin;password=123456");
System.out.println("adminAccount: " + session.getAttribute("adminAccount"));
System.out.println("test1: " + session.getAttribute("test1"));
System.out.println("test2: " + session.getAttribute("test2"));
System.out.println("test3: " + session.getAttribute("test3"));
return "demo";
}
前台代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
%>
<% Object sessionValues=session.getAttribute("adminAccount"); %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="zh-CN">
<head>
<title>登陆</title>
<link href="<%=basePath%>/resources/css/bootstrap.min.css" rel="stylesheet">
<link href="<%=basePath%>/resources/css/bootstrap-theme.min.css" rel="stylesheet">
<%-- <link href="<%=basePath%>/resources/css/login.css" rel="stylesheet"> --%>
<script src="<%=basePath%>/resources/js/jquery-1.11.3.min.js"></script>
<script src="<%=basePath%>/resources/js/bootstrap.min.js"></script>
<script src="<%=basePath%>/resources/js/jquery.cookie.js"></script>
<script src="<%=basePath%>/resources/js/jquerySession.js"></script>
<script>
$(document).ready(function(){
$.session.set("test1","testcontent");
var session = $.session.get('adminAccount');
var session2 = "${adminAccount}";
var test1 = $.session.get('test1');
<% session.setAttribute("test2", "this is test2");
%>
$("button:eq(0)").click(function(){
alert(session);
alert(session2);
alert(test1);
<% session.setAttribute("test3", "this is test3");
%>
$("ol").append("<li>show session by el:adminAccount = ${adminAccount}</li>")
$("ol").append("<li>show session by el:test1 = ${test1}</li>")
$("ol").append("<li>show session by jq:test1 = " + test1 +"</li>")
return null;
});
});
</script>
</head>
<body>
<button>show session</button>
<ol>
<li>show session by asp:adminAccount = <%=sessionValues %></li>
<li>show session by el:adminAccount = ${adminAccount}</li>
</ol>
</body>
</html>