More Tech articles here: Google Da
In this post I will show a simple code and explain how to pass information between Jsp and Servlet. This information sharing is highly essential for many programming scenarios encountered in real time.
We will pass information to and fro between servlets and jsp using sessions and servlet context information.
I presume you know how to invoke a servlet from a jsp page by making entries in web.xml in Tomcat Container.
If you are using Eclipse, the latter will take care of the mapping, though in some cases you would have to manually make the entry in web.xml (Deployment Descriptor).
We got 4 files here:
- We will pass a value from Page1JSP to Page2Servlet.
- Then we will pass another value from Page2Servlet to Page3JSP.
- And finally, we pass a value from Page3JSP to Page4Servlet.
- In addition, we will be accessing a value in Page4Servlet that has been sent from Page1JSP to Page2Servlet.
Lets see some action!
This is the form we have in Page1JSP.jsp
Notice that we are passing the form data “tName” to a servlet named “Page2Servlet”.
Output of Page1JSP.jsp:
We obtain form data sent by Page1JSP.jsp in the service() method of the servlet:
Next, we create a session and set an attribute named “Page2SessAttr”
Page2SessAttr contains the form value received from Page1Jsp. You can also set any another value into it.
Next, we obtain the Servlet Context and set an attribute in it, so that when we pass a servlets context to a Jsp , the latter would be able to access the attribute set and “forwarded” by the servlet.
Page3Jsp will receive the entire context of the servlet, that includes even the attributes set by the latter.
We will access the values sent by Page2Servlet both by the session and through the servlet context.
In Pag3Jsp, we have just accessed that session and NOT created a new session. This you can know from the following line in the above code:
HttpSession sess = request.getSession(false);
The parameter “false” indicates that this is an already created session.
Finally, In Page4Servlet.java
We will access the session attributes set by Page3JSP.jsp
In addition, “recvStr2” contains the value of “Page2SessAttr” set in Page2Servlet session.
The final output I see in my Eclipse console is:
I hope, this piece of material was clear enough to explain you how to share values between Servlets and Jsp. There may be other methods of sharing too, but this seems fairly simple to me.
If you are not clear with my explanations in tutorial just read follow the code snippets alone.
Share this post if you like it!