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 {
	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>

This Servlet tutorial was added on 08/04/2009.

previous post: What are the causes of exceptions in java?

next post: Differentiate JVM JRE JDK JIT

62 comments on “Servlet JSP Communication

  1. I love this article a lot. JSP Servlet communication nicely explained.

  2. Really useful article on Servlet JSP Communication

  3. This is really very handy article.
    Vector and String example really helped me a lot.
    Thanks
    -Shailesh

  4. we can write like request.getRequestDispatcher() then you have written like this? any special use?

  5. Nice One on Servelt JSP communication…

  6. really nice…very easy to understand for beginners

  7. I dint understand it.. I got error when i executed it.. so pls can u explain the code in a simpler way.?

  8. it is very useful……easy to understand
    thank u…………

  9. good article , very easily explained, keep up the great job site owners, more questions on servlets would have helped more.

  10. Nice website……….
    easy to learn jsp servlet communication……..

    Ami Tiwari

  11. good explanation …..its very useful for beginners

  12. plz tell me the difference between doGet and doPost

  13. Hi,

    This is kalyan i am new for java.I am learning java just from last month, i have good knowledge in Flash Action Script so that the reason i learn java. But i am getting some problems in SERVOLETS and JSP
    plz help me how to connect between servolets and jsp.

    Thanks & Regards

    Kalyan Kumar.
    Hyderabad.

  14. this website is really great. i knew about getting datas from servlet to jsp through this site only. i can,t get it from any other sites. great job joe… thanks

  15. This website is very nice to read. there is no distrub and interub by displaying adds. so it is usefull to learners

  16. Very well explained code example. Simple yet sophisticated!

  17. It’s Very Useful for me ……….

    Thank You so much..

  18. Nice example..for Servlet and Jsp understanding…

  19. hi am creting a dashboard using servlts and jsp..i am new to java..
    i need to get values from database and then depending upon the values i have to show on screen the colour changes…example if some value is 7:00am a file came , so if it is late a circle should be shown with colur Red.
    i have creted a sample program to get the values from database but i dont know how to compare the values coming from database and to show on screen.
    can u guide me….
    elp….

  20. what is Inter-servlet communication.?

  21. sir i want software requirement specifications for java 6.0 software
    will u post me answer sir??

    thanku

  22. Connection myConn=null;
    Statement myStmt=null;
    ResultSet myRs=null;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType(“text/html;charset=UTF-8″);
    PrintWriter out = response.getWriter();
    try {
    /*
    * TODO output your page here. You may use following sample code.
    */

    /*out.println(“”);
    out.println(“”);
    out.println(“Servlet userDetail”);
    out.println(“”);
    out.println(“”);
    out.println(“Servlet userDetail at ” + request.getContextPath() + “”);
    out.println(“”);
    out.println(“”);*/

    Class.forName(“com.mysql,jdbc.Driver”);

    myConn=DriverManager.getConnection(“jdbc.mysql://localhost:3306/wp2″,”root”,””);

    myStmt=myConn.createStatement();

    String query=”select * from userdetails”;

    myRs=myStmt.executeQuery(query);

    while(myRs.next());
    {
    out.println(“Username”+myRs.getString(“uname”));
    out.println(“Password”+myRs.getString(“upass”));
    out.println(“”);
    }

    }
    catch(Exception e)
    {
    System.out.println(“Exception”+e);
    }

    finally {
    try
    {
    myConn.close();
    myStmt.close();
    myRs.close();
    }
    catch(Exception e)
    {
    System.out.println(“Exception from finally”+e);
    }

    what’s wrong with this program.. Why I can’t connect to server?? I using localhost myself and use wamp server. Thx

    • check Your library folder. A jar file required for the mysql database..

  23. nice one easily understood RequestDispatcher usage from this tutorial

  24. Sir, can u plz explain me what is ServletContext Listener with use and example also

    Thanks

  25. joe i want know that what is the relation between finalize method and garbage collector.

  26. I configured similar but i am unable to retrieve string on jsp can please help me.

    FYI: I do following

    request.setAttribute(“QueryURL”, finalquery);
    //getServletContext().getRequestDispatcher(“/NoLimitSearch.jsp”).forward(request, response);
    RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher(“/NoLimitSearch.jsp”);
    reqDispatcher.forward(request,response);

    and on NoLimitSearch.jsp:

    finalquery = (String) request.getParameter(“QueryURL”);

    System.out.println(“QUERY: “+ finalquery);

    Result:
    QUERY: null

    why???

  27. HI JOE,

    I HAVE DECIDED TO BUILD AN APPLICATION USING

    SWINGS + SERVLETS + HIBERNATE.

    I HAVE KNOWLEDGE OF CREATION USING THE FOLLOWING

    JSP + SERVLETS + HIBERNATE.

    BUT I DONT KNOW HOW TO CALL SERVLET FROM A SWING.

    IF YOU HAVE A CRUD EXAMPLE PLS SHARE

  28. sir , thanks for your service. can u send me servlet projects if available.

  29. Very nice explanation…. really usefull.. Thank you..

  30. Very useful article, but when I try to run it I get the following exception: “java.lang.IllegalStateException: Cannot forward after response has been committed”. Any idea what’s going on? Thanks in advance

  31. Thank you for nice article. It’s very useful for beginners.

  32. Best Article about servlet JSP! Thanks

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>