Question

I have a parent jsp a.jsp which includes another jsp b.jsp. I am calculating some values in b.jsp which needs to be used in parent jsp a.jsp , which will pass this calculated value to another jsp say c.jsp. How can I evaluate value in child jsp and pass it to parent jsp before that page completely loads?

Was it helpful?

Solution

How are you including the "child" jar inside the parent? static or dynamic import?

if you have

<%@ include file="myFile.jsp" %>

change it by

<jsp:include file="myFile.jsp" />

then in the parent set a property in the request (not in the session, that would be "dirtier"):

<% request.setAttribute("attrName", myValue) %>

finally, in the "child" jsp:

<% myValue = (MyValueType)request.getAttribute("attrName") %>

OTHER TIPS

If you need to pass an attribute between including and included jsp (and viceversa)you should use the page context, which is the more short context (from lifecycle perspective)

You can set variables in the request in b.jsp, and use them in parent.jsp. But you can only use them in the parent jsp after the <jsp:include> tag. Remember that this is all evaluated on the server side, so when you say "before that page completely loads," you can be guaranteed that the server has evaluated it before the browser has loaded it. If you mean that you want to delay evaluation on the server until some code below it is evaluated, that's not going to be possible. At least not like this.

b.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="myVar" scope="request" value="Hello"/>

parent.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<jsp:include page="b.jsp"></jsp:include>

<span>
    The value is ${requestScope.myVar}.
</span>

You could you session scope to accomplish this.

(b.jsp)

session.setAttribute("value",value);

(c.jsp)

session.getAttribute("value");

However, I would recommend doing some major restructuring instead. In your example, the value of your data depends on the order of the elements on the page. If you ever need to re-arrange things (for instance, moving the b.jsp include after the c.jsp include), you risk breaking the business logic.

A good pattern for web development is a model-view-controller pattern. The "controller" determines what page should be displayed, the "model" calculates all the data and makes it available, and the "view" does the display and formatting.

I would recommend reviewing this article, which is helpful for understanding why MVC is a valuable approach: http://www.javaranch.com/journal/200603/Journal200603.jsp#a5

Edit: As other users have mentioned, request scope would be cleaner than session scope. However, I still recommend determining the value first before writing any display content.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top