Monday, April 26, 2010

Servlet JSP Communication

getServletConfig().getServletContext().getRequestDispatcher(“jspfilepathtoforward”).forward(request, response);

The above line is essence of the answer for “How does a servlet communicate with a JSP page?”

When a servlet jsp communication is happening, it is not just about forwarding the request to a JSP from a servlet. There might be a need to transfer a string value or on object itself.

Following is a servlet and JSP source code example to perform Servlet JSP communication. Wherein an object will be communicated to a JSP from a Servlet.

Following are the steps in Servlet JSP Communication:

1. Servlet instantiates a bean and initializes it.
2. The bean is then placed into the request
3. The call is then forwarded to the JSP page, using request dispatcher.

Example Servlet Source Code: (ServletToJSP.java)

public class ServletToJSP extends HttpServlet {
02. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
03.
04. //communicating a simple String message.
05. String message = "Example source code of Servlet to JSP communication.";
06. request.setAttribute("message", message);
07.
08. //communicating a Vector object
09. Vector vecObj = new Vector();
10. vecObj.add("Servlet to JSP communicating an object");
11. request.setAttribute("vecBean",vecObj);
12.
13. //Servlet JSP communication
14. RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("/jsp/javaPapers.jsp");
15. reqDispatcher.forward(request,response);
16. }
17.}

Example JSP Source Code: (javaPapers.jsp)

<-html>
02.<-body>
03.<%
04. String message = (String) request.getAttribute("message");
05. out.println("Servlet communicated message to JSP: "+ message);
06.
07. Vector vecObj = (Vector) request.getAttribute("vecBean");
08. out.println("Servlet to JSP communication of an object: "+vecObj.get(0));
09.%>
10.<-/body>
11.<-/html>

No comments: