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.

«

»

Comments on “Servlet JSP Communication”

  1. Omkar

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

  2. Anonymous

    Really useful article on Servlet JSP Communication

  3. shailesh

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

  4. Nagu

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

  5. Srikanth S

    Nice One on Servelt JSP communication…

  6. alok

    really nice…very easy to understand for beginners

  7. Chetan

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

  8. swati

    great article!!!

  9. guru

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

  10. Asif

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

  11. Ami Tiwari

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

    Ami Tiwari

  12. pravee

    Awesome explanation

    Thanks lot…

  13. Nitheesh R

    Good explanation, thanks

  14. fAHEEM

    Very nice……
    I love this

  15. Kishor

    Really helpful…

  16. thanks leave by a chinese java beginer .

  17. abinaya

    good explanation …..its very useful for beginners

  18. sirisha

    plz tell me the difference between doGet and doPost

  19. aatish

    good one

  20. Ramesh

    good Example

  21. Prasath

    *Nice and useful one…………

  22. Kalyan

    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.

  23. venu

    good example

  24. Gopal

    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

  25. Anonymous

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

  26. Anonymous

    Very well explained code example. Simple yet sophisticated!

  27. Ravindar

    It’s Very Useful for me ……….

    Thank You so much..

  28. Ramesh

    Nice example..for Servlet and Jsp understanding…

  29. Anonymous

    Excellent Superb awesome

  30. Praveen

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

  31. pavan_krishna

    what is Inter-servlet communication.?

  32. srinivas

    nice example easy to understood.

  33. Anonymous

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

    thanku

  34. Anonymous

    very nice

  35. Anonymous

    waste waste waste

  36. Anonymous

    i like java and JSP .too.

  37. Siddhartha

    Very nice……….

  38. ikramlim

    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

  39. abhi

    nice one..

  40. Venkata Tekkem

    nice one easily understood RequestDispatcher usage from this tutorial

  41. Kavita

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

    Thanks

  42. u r way better than ranga

  43. Bharat

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

  44. Gaurav

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

  45. easy understanding u r answers sir…,

  46. Syed

    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

  47. Michel

    nice topic!! Thank you!

  48. Mahima

    Very nice example

  49. ritesh

    really helpful

  50. venkat

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

  51. AmalaChris

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

  52. Blasko

    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

  53. manju

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

  54. Raymundo

    Best Article about servlet JSP! Thanks

Your Comment