Servlet JSP Communication

Last modified on September 30th, 2014 by Joe.

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>

Comments on "Servlet JSP Communication"

  1. Omkar says:

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

  2. Anonymous says:

    Really useful article on Servlet JSP Communication

  3. shailesh says:

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

  4. Nagu says:

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

  5. Srikanth S says:

    Nice One on Servelt JSP communication…

  6. alok says:

    really nice…very easy to understand for beginners

  7. Chetan says:

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

  8. swati says:

    great article!!!

  9. guru says:

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

  10. Asif says:

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

  11. Ami Tiwari says:

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

    Ami Tiwari

  12. pravee says:

    Awesome explanation

    Thanks lot…

  13. Nitheesh R says:

    Good explanation, thanks

  14. fAHEEM says:

    Very nice……
    I love this

  15. Kishor says:

    Really helpful…

  16. lapa says:

    thanks leave by a chinese java beginer .

  17. abinaya says:

    good explanation …..its very useful for beginners

  18. sirisha says:

    plz tell me the difference between doGet and doPost

  19. gowtham says:

    nice web design

  20. aatish says:

    good one

  21. Ramesh says:

    good Example

  22. Prasath says:

    *Nice and useful one…………

  23. Kalyan says:

    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.

  24. venu says:

    good example

  25. Gopal says:

    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

  26. Anonymous says:

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

  27. Anonymous says:

    Very well explained code example. Simple yet sophisticated!

  28. Ravindar says:

    It’s Very Useful for me ……….

    Thank You so much..

  29. Ramesh says:

    Nice example..for Servlet and Jsp understanding…

  30. Anonymous says:

    Excellent Superb awesome

  31. Praveen says:

    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….

  32. pavan_krishna says:

    what is Inter-servlet communication.?

  33. srinivas says:

    nice example easy to understood.

  34. Anonymous says:

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

    thanku

  35. Anonymous says:

    very nice

  36. Anonymous says:

    waste waste waste

  37. Anonymous says:

    i like java and JSP .too.

  38. Siddhartha says:

    Very nice……….

  39. ikramlim says:

    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

  40. toto says:

    lol

  41. abhi says:

    nice one..

  42. Venkata Tekkem says:

    nice one easily understood RequestDispatcher usage from this tutorial

  43. Kavita says:

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

    Thanks

  44. prashant says:

    ja re diwane

  45. prashant says:

    joe u r handsome

  46. prashant says:

    u r way better than ranga

  47. Bharat says:

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

  48. venu says:

    add ur DB password to getConnection

  49. Gaurav says:

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

  50. Rammohan says:

    easy understanding u r answers sir…,

  51. gorityala ramana says:

    sorry ,we want to get more clarity on the disscuss of the topic

  52. Syed says:

    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

  53. Arun says:

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

  54. Michel says:

    nice topic!! Thank you!

  55. Mahima says:

    Very nice example

  56. ritesh says:

    really helpful

  57. venkat says:

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

  58. AmalaChris says:

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

  59. Blasko says:

    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

  60. manju says:

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

  61. Raymundo says:

    Best Article about servlet JSP! Thanks

Comments are closed for "Servlet JSP Communication".