How to return a value from servlet
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   hassan_hassan
Posted On:   Monday, October 15, 2001 10:41 PM

Hi all

How to make a servlet to return a value to calling jsp.


Since doPost is void method which is calling another method in the same servlet, that method returns a value to doPost method. i dont know how will i pass this value to calling jsp.


is ther any other method which cannot be void type..



Can i call a particular method in the servlet from jsp , like calling a method in java class (usebean).



pls advice

Hassan

Re: How to return a value from servlet

Posted By:   Shahram_Khorsand  
Posted On:   Monday, October 15, 2001 11:20 PM

There are couple of ways to do this.


  1. You can put the information you like in a HTTPSession object. This object is created for you and stays with the user during the time they are in the site. This is done like this:

    HttpSession s = request.getSession(true);

    s.setAttribute("returnVal", callMethod());


    The first row creates the session if there are no sessions. Next row sets the value you like in to the session object. Remember that in the JSP page you have to cast this object back to whatever object it is. All "things" in a session object are stored as java.lang.Objects.

    here is how that is done inside the JSP page:

    myObject = (myObject)

    session.getAttribute("returnVal");

  2. The other way of doing this is to put the value in the request object. It is similar to the previous example, only it is the request object.

    Here is how that is done:

    RequestDispatcher rd = getServletContext().getRequestDispatcher("/yourjsppage.jsp");

    request.setAttribute("myObject", getMyObject());

    rd.forward(request, response);


    The first row gets the requestDispatcher, the second line adds your object to the request object and the last line forwards the request.

    in the JSP page you use the "request" object like this:

    myObject = (myObject)request.getAttribute("myObject");


Good Luck!
About | Sitemap | Contact