JSP获取Session中的值有三种方法
- 在JSP页面使用Java代码session.getAttribute()或者request.getSession.getAttribute()获取,需要用<%=%>把Java代码包起来
- 用EL表达式获取
EL 存取变量数据的方法很简单,例如:${testString}。它的意思是取出某一范围中名称为testString的变量。如果我们没有指定哪一个范围的testString,它会默认值从Page 范围找,假如找不到,再依序到Request、Session、Application范围。假如途中找到testString,就直接回传,不再继续找下去。但是如果全部范围都没有找到,就会回传NULL。EL表达式做了优化,页面上会显示空白,而不是显示NULL。
JSP域对象 | EL中的名称 | 范例 | 说明 |
---|---|---|---|
Page | pageScope | ${pageScope.testString} | 取出PageContext 中的testString变量 |
Request | requestScope | ${requestScope.testString} | 取出HttpServletRequest 中的testString变量 |
Session | sessionScope | ${sessionScope.testString} | 取出HTTPSession中的testString变量 |
Application | applicationScope | ${applicationScope.testString} | 取出ServletContext 中的testString变量 |
所以我们下面的例子中都指定了在sessionScope取值
- 用struts标签获取
例子
session中值的类型为String
//java代码
session.setAttribute("testString","testValue");
//JSP页面代码
//使用Java代码获取
<%=session.getAttribute("testString")%>
<%=request.getSession.getAttribute("testString");%>
//或者EL表达式获取
${sessionScope.testString}
//或者用struts标签获取
<s:property value="#session.testString"/>
//这样就能用js调用
<script language="JavaScript">
function getTestValue(){
var testValue='<%=session.getAttribute("testString")%>';
alert(testValue);
}
</script>
session中值的类型为List
//java代码
List<String> list= new ArrayList<String>();
list.add("Max");
list.add("Male");
session.setAttribute("testList",list);
//JSP页面代码
//使用Java代码获取
<%=((List<String>) session.getAttribute("testList")).get(0)%>
<%=((List<String>) request.getSession.getAttribute("testList")).get(1)%>
//或者EL表达式获取
${sessionScope.testList[0]}//Max
${sessionScope.testList[1]}//Male
//或者用struts标签获取
<s:if test="#session.testList[1] == 'Max'"/>
session中值的类型为Map
//java代码
Map<String, String> map = new HashMap<String, String>();
map.put("name","Max");
map.put("sex","Male");
session.setAttribute("testMap",map);
//JSP页面代码
//使用Java代码获取
<%=((Map<String, String>) session.getAttribute("testMap")).get("name")%>
<%=((Map<String, String>) request.getSession.getAttribute("testMap")).get("sex")%>
//或者EL表达式获取
${sessionScope.testMap.name}
//或者用struts标签获取
<s:if test="#session.testMap.name == 'Max'"/>
session中的值类型为对象
//java代码
User user = new User();
user.setName("Max");
user.setSex("Male");
session.setAttribute("user ",user );
//JSP页面代码
//使用Java代码获取
<%=((User) session.getAttribute("user")).get("name")%>
<%=((User) request.getSession.getAttribute("user")).get("sex")%>
//或者EL表达式获取
${sessionScope.user.name}
//或者用struts标签获取
<s:if test="#session.user.name != null"/>