Since past few days, I was working on some Java Server Pages, which are linked with each other. Many times I have to include some JSPs in one JSP. While doing so, I need to call the variables defined in one JSP, in those JSP’s which are included one. I thus have to pass these parameters from one JSP to another at the time of Including those.
I searched for the solutions, and found many different ways of doing so.
For including another JSP into a JSP I used the following command in FirstJSP.jsp
<jsp:include page=”SecondJSP.jsp”/>
I searched for it and found many different ways of doing so.
1. JSP:Param
<jsp:include page=“SecondJSP.jsp” />
<jsp:param name=“name” value=“Sulabh Jain” />
<jsp:param name=“age” value=“24″ />
</jsp:include>
The above code will help in setting the values of param1 and param2 as value1 and value2
which can be called or retrieved in SecondJSP.jsp using,
<%
String myName= request.getParameter(“name”)
String myAge= request.getParameter(“age”)
%>
These can be printed in JSP using ‘equals to’ sign (=) with percentage tags,
My Name is <%=myName%>
My Age is <%=myAge%>
2. JSP:Forward
It also behaves similar to jsp:param
<jsp: forward page=”SecondJSP.jsp”>
<jsp: param name=”name” value=”Amar Patel”/>
<jsp: param name=”age” value=”15″/>
</jsp: forward>
Limitations of above two methods :
This method of passing parameters can be used only for Static variables. For eg.
if we have a dynamic variable declared in JSP we cannot pass it using jsp:param
Here it got little difficult,
Now I need to pass dynamic variables which I defined in the first JSP.
The third method provides solution to it.
3. request.setAttribute
Here we will use an object of javax.servlet.http.HttpServletRequest class named as request.
calling the public abstract void setAttribute(java.lang.String name, java.lang.Object o) method we can set the String name as an attribute.
<%
String name = “Sulabh Jain”;
request.setAttribute(“myName”, name);
%>
Now we can easily get in in SecondJSP as
<%
String nameInNewJSP = request.getAttribute(“myName”).toString();
%>
toString is used here to convert the object into string.
References:
1. Passing parameters, http://www.ezdia.com/Passing_parameters_to_JSP_using_jsp%3Aparam/Content.do?id=968
2. Calling a new JSP, http://www.ezdia.com/Calling_a_new_JSP/Content.do?id=969
3. JSP exercises, http://www.ezdia.com/JSP_Exercises/Content.do?id=806
Please post your comments, on the above provided code, and suggest if there exists better or more options.
Thanks

