How to return a value from a servlet to a JSP?
Shahram Khorsand There are couple of ways to do this.
- 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");
- 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");