View Single Post
  #2 (permalink)  
Old 08-01-2007, 11:47 PM
Venkat Venkat is offline
D-Web Master
 
Join Date: Mar 2007
Posts: 350
Venkat is on a distinguished road
Default Re: How to pass data (including JavaBeans) to a JSP from a servlet?

hi
Invoking a JSP Page from a Servlet

You can invoke a JSP page from a servlet through functionality of the standard javax.servlet.RequestDispatcher interface. Complete the following steps in your code to use this mechanism:

1. Get a servlet context instance from the servlet instance:

ServletContext sc = this.getServletContext();

2. Get a request dispatcher from the servlet context instance, specifying the page-relative or application-relative path of the target JSP page as input to the getRequestDispatcher() method:

RequestDispatcher rd = sc.getRequestDispatcher("/jsp/mypage.jsp");

Prior to or during this step, you can optionally make data available to the JSP page through attributes of the HTTP request object. See "Passing Data Between a JSP Page and a Servlet" below for information.
3. Invoke the include() or forward() method of the request dispatcher, specifying the HTTP request and response objects as arguments. For example:

rd.include(request, response);

or:

rd.forward(request, response);

The functionality of these methods is similar to that of jsp:include and jsp:forward tags. The include() method only temporarily transfers control; execution returns to the invoking servlet afterward.

Note that the forward() method clears the output buffer.

Notes:

* The request and response objects would have been obtained earlier, using standard servlet functionality such as the doGet() method specified in the javax.servlet.http.HttpServlet class.

* This functionality was introduced in the servlet 2.1 specification.

Passing Data Between a JSP Page and a Servlet

The preceding section, "Invoking a JSP Page from a Servlet", notes that when you invoke a JSP page from a servlet through the request dispatcher, you can optionally pass data through the HTTP request object.

You can accomplish this using either of the following approaches:

* You can append a query string to the URL when you obtain the request dispatcher, using "?" syntax with name=value pairs. For example:

RequestDispatcher rd =
sc.getRequestDispatcher("/jsp/mypage.jsp?username=Smith");

In the target JSP page (or servlet), you can use the getParameter() method of the implicit request object to obtain the value of a parameter set in this way.
* You can use the setAttribute() method of the HTTP request object. For example:

request.setAttribute("username", "Smith");
RequestDispatcher rd = sc.getRequestDispatcher("/jsp/mypage.jsp");

In the target JSP page (or servlet), you can use the getAttribute() method of the implicit request object to obtain the value of a parameter set in this way.

Notes:

You can use the mechanisms discussed in this section instead of the jsparam tag to pass data from a JSP page to a servlet.
Reply With Quote