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.
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)
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 { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //communicating a simple String message. String message = "Example source code of Servlet to JSP communication."; request.setAttribute("message", message); //communicating a Vector object Vector vecObj = new Vector(); vecObj.add("Servlet to JSP communicating an object"); request.setAttribute("vecBean",vecObj); //Servlet JSP communication RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("/jsp/javaPapers.jsp"); reqDispatcher.forward(request,response); } }Example JSP Source Code: (javaPapers.jsp)
<html> <body> <% String message = (String) request.getAttribute("message"); out.println("Servlet communicated message to JSP: "+ message); Vector vecObj = (Vector) request.getAttribute("vecBean"); out.println("Servlet to JSP communication of an object: "+vecObj.get(0)); %> </body> </html>
No comments:
Post a Comment