EL ExpressionFactory, scopes, JSTL forEach tag, iterated variable: where is?
I am working with ExpressionFactory inside my program, and I wan to make ValueExpressions and variables be accessible from JSP with EL expressions.
I can't understand something: looks like my variables I put way override normal variables, for example, those set by forEach tag when iterating. I am thinking that my code puts user in a pageScope, and obvoiusly so does forEach tag, but I am wrong.
How should I work with factory and value expressions, so that I can access variables unless they are overridden, not vice versa like in the following example?:
<%@page import="javax.el.ValueExpression"%>
<%@page import="javax.el.ELContext"%>
<%@page import="javax.el.ExpressionFactory"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Check Scopes</title>
</head>
<body>
<%
ExpressionFactory ef = JspFactory.getDefaultFactory().
getJspApplicationContext(application).getExpressionFactory();
ELContext ec = pageContext.getELContext();
ValueExpression ve = ef.createValueExpression(ec, "humangus", String.class);
pageContext.getELContext().getVariableMapper().setVariable("user", ve);
String[]users = new String[]{"mike", "bob", "kate"};
pageContext.setAttribute("users", users);
%>
<h3>List of Users:</h3>
<c:forEach var="user" items="${users}" varStatus="status">
${status.count}:
without specifying scope: ${user},
from page scope: ${pageScope.user}<br/>
</c:forEach>
</body>
</html>
This produces the following:
List of Users:
1: wit开发者_如何学JAVAhout specifying scope: humangus, from page scope: mike
2: without specifying scope: humangus, from page scope: bob
3: without specifying scope: humangus, from page scope: kate
I played around with your code.
<%
pageContext.setAttribute("user", "humangus");
String[]users = new String[]{"mike", "bob", "kate"};
pageContext.setAttribute("users", users);
%>
Before forEach loop user is ${user}!<br/>
<c:forEach var="user" items="${users}" varStatus="status">
${status.count} user is ${user}<br/>
</c:forEach>
After forEach loop user is ${user}!
Output: Before forEach loop user is humangus! 1 user is mike 2 user is bob 3 user is kate After forEach loop user is !
??? Curiously, no value is found after the forEach loop.
精彩评论