Calling a Servlet From a JSP and Vice-Versa

Servlets and JSPs are the defacto method of server side computing today. Servlets form the logic of the application code and formatting for output is done with the help of JSPs (Java Server Pages). Because these two technologies abstract code logic from presentation, communication between the two has led to rapid code development regarding the true principles of Object Oriented Programming.

The trick to understanding JSPs is keeping in mind that every JSP is ultimately compiled into a Servlet. The main thing then becomes understanding the way a servlet communicates with a JSP and vice-versa. This becomes even more important when sending the output of a calculation in a servlet to a JSP, or when redirecting a user to a servlet from a JSP.

Calling a JSP from a Servlet, or vice-versa, can be done using the RequestDispatcher interface, which is part of the Servlet 2.2 specification. Following is the code for sending output to a JSP page from a servlet:

 //Some calculation ; Maybe even a call to EJB(s) javax.servlet.RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: