Setting parent jsp variables in child jsp

I have a parent jsp a.jsp that includes another jsp b.jsp. I compute some values โ€‹โ€‹in b.jsp that should be used in the parent jsp a.jsp, which will pass this computed value to another jsp, say c.jsp. How can I evaluate the value in the child jsp and pass it to the parent jsp before this page fully loads?

+4
source share
4 answers

How do you turn on the "daughter" jar inside the parent? static or dynamic import?

if you have

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

change it to

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

then in the parent set the property in the request (not in the session, it will be "dirtier"):

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

finally in the "child" jsp:

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

If you need to pass an attribute between included and included jsp (and vice versa), you should use the page context, which is a shorter context (in terms of life cycle)

+1
source

You can set the 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 all of this is evaluated on the server side, so when you say โ€œbefore this page is fully loadedโ€, you can be sure that the server rated it before the browser loaded it. If you mean that you want to postpone the evaluation on the server until some code below is evaluated, this will not be possible. At least not so.

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> 
+1
source

You could use the session features to do this.

(b.jsp)

 session.setAttribute("value",value); 

(c.jsp)

 session.getAttribute("value"); 

However, I would recommend a major restructuring. In your example, the meaning of your data depends on the order of the elements on the page. If you ever need to reinstall things (for example, moving b.jsp turns on after turning on c.jsp), you run the risk of breaking the business logic.

A good template for web development is a model-controller-controller. The "controller" determines which page should be displayed, the "model" calculates all the data and makes it available, and the "view" displays and formats.

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

Edit: as other users mentioned, the request area will be cleaner than the session area. However, I still recommend that you first determine the value before writing any display content.

-one
source

Source: https://habr.com/ru/post/1492788/


All Articles