开发者

Cannot access variable inside the included JSP

I am using Spring 2.5 in my application. In the view I have main jsp in which I have included another jsp. I have declared a variable using c:set tag in main jsp which I can not access inside the jsp. Below is code main.jsp

<c:set var="hPediquestStudy"><spring:message code="study.hpediquest.mapping" /></c:set>
<c:set var="currentStudy" value='<%=(String)session.getAttribute("currentStudy")%>'/>
<html>
<head>
</head>
<body>
<c:if test="${currentStudy eq hPediquestStudy}">
  Variables are equal
</c:if>
<c:if test="${currentStudy ne hPediquestStudy}">
  Variables are not equal
</c:if>
<jsp:include page="/WEB-INF/jsp/included.jsp"></jsp:include&开发者_StackOverflow社区gt;
</body
</html>

included.jsp

<c:if test="${currentStudy eq hPediquestStudy}">
   hPediquestStudy Variable is accessible
</c:if>
 <br/>currentStudy : ${currentStudy}
 <br/>hPediquestStudy : ${hPediquestStudy}

I am getting output

Variables are equal

currentStudy : hPediquest

hPediquestStudy :

  1. Why on main jsp both values are equal while in included jsp I dont see its value?
  2. Why currentStudy displays its value inside the included jsp?
  3. is there any solution which helps me to access the variable set in the parent jsp ans can be accessed in the included jsps?

I can see the value of hPediquestStudy value if I set that variable in included jsp like in main jsp. But I dont want to set it every time when I include the jsp. Please help


Why on main jsp both values are equal while in included jsp I dont see its value?

Because <c:set> by default stores them in the page scope.


Why currentStudy displays its value inside the included jsp?

Because it's available as session attribute as well.


is there any solution which helps me to access the variable set in the parent jsp ans can be accessed in the included jsps?

You need to set the scope attribute of <c:set> to request or above. The (default) page scope is exposed to current JSP only, not any included JSPs.


Note that the line

<c:set var="currentStudy" value='<%=(String)session.getAttribute("currentStudy")%>'/> 

is unnecessary. The ${currentStudy} will already scan for variables in page, request, session and application scopes. As you've apparently already set it in the session scope, you don't need to copy it into the page scope. So, just remove that line. All with all, your top 2 <c:set> lines should be replaced with this single line:

<c:set var="hPediquestStudy" scope="request"><spring:message code="study.hpediquest.mapping" /></c:set>

and then it'll work the way you intended.

See also:

  • Our EL wiki page
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜