DOC

JSP - FAQ (2)

By Antonio Morgan,2014-09-16 16:54
9 views 0
JSP - FAQ (2)

    JSP - FAQ (2)

作者;jspfuns

日期;2000-8-10 17:49:53

10) How do you invoke a JSP page from a servlet? TOC

(Contributed by: Thomas-Bernhard.O-Hare@Dresdner-Bank.com)

    After scanning through archives of the JSP mailing list to no effect I finally remembered that I'd pasted this example into a document I wrote. It was originally sent by Satish Dharmaraj of Sun to show the model 2 approach (as described in the 0.92 specification): how to pass data from a servlet

to a JSP.

    Create a directory called model1/ under the samples/ directory. Place foo.jsp and Foo.java inside this directory.

    Compile FooServlet.java and place FooServlet.class in TOP/servlets/directory.

Then invoke using http://host:8080/servlet/FooServlet

In this example, FooServlet creates a list and then stores the

    result in Foo.class. Foo.Class is then passed as a datasource to

    foo.jsp.

The sources are:

1) FooServlet.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import model1.Foo;

public class FooServlet extends HttpServlet

{

public void service(HttpServletRequest req, HttpServletResponse

    res)

throws ServletException, IOException

{

String s[] = new String[] {"blue", "green", "red"};

Foo f = new Foo(s);

req.setAttribute("foo", f);

getServletContext().getRequestDispatcher("/samples/model1/foo.jsp"

    ).forward

(req, res);

}

}

2) foo.jsp

3) Foo.java

package model1;

public class Foo {

String s[];

public String[] getList() { return s; }

public Foo(String s[]) { this.s = s; }

}

(from "Oare, Thomas Bernhard" <Thomas-Bernhard.O-Hare@Dresdner-

    Bank.com>)

    11) How do you pass data (including beans) to a JSP from a servlet? TOC

    There are actually three different ways to do it, depending on how long the reference should last, and which JSP pages (and servlets,

    for that matter) should be able to see it. In each of the cases, assume that "myBean" is a reference to the bean you want to send, and that "theBean" is the key I'm going to use to store the bean under (from the servlet perspective), and use as the identity of

    the bean in the JSP page.

    These techniques are portable to any environment compliant with the servlet API 2.1 and JSP 1.0 specifications. In each case, the passing

works from servlet->JSP, servlet->servlet, JSP->JSP, or JSP-

    >servlet transitions.

(1) Request Lifetime

    Use this technique to pass beans that are relevant to this particular request to a bean you are calling through a request dispatcher (using either "include" or "forward"). This bean will disappear after processing this request has been completed.

SERVLET:

request.setAttribute("theBean", myBean);

RequestDispatcher rd =

getServletContext().getRequestDispatcher('/thepage.jsp");

rd.forward(request, response);

JSP PAGE:

/>

(2) Session Lifetime

    Use this techni