Calling JSP from servlet

Discussions

Web tier: servlets, JSP, Web frameworks: Calling JSP from servlet

  1. Calling JSP from servlet (2 messages)

    Can any one help in calling a JSP page from a servlet?

    TIA,
    sn

    Threaded Messages (2)

  2. Calling JSP from servlet[ Go to top ]

    Dear Friend,

    Only JSDK 2.2 can call JSP from a servlet using the interface RequestDispatcher. ie, you should download the new API.

    Ques.

    How do you invoke a JSP page from a servlet?
    How to pass data from a servlet to a JSP?.

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

         <html>
         <usebean name=foo type=model1.Foo lifespan=page>
         </usebean>
         <ul>
         <loop property=foo:list propertyelement=x>
         <li> <display property=x>
         </loop>
         </ul>
         </html>

         3) Foo.java

         package model1;

         public class Foo {

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



    With Care,
    RAJEEV.S.
    Trivandrum, Kerala, India.
    (rajeevsmcp at usa dot net)
  3. Calling JSP from servlet[ Go to top ]

    using request dispatch object we can call a jsp page from a servlet.
    refer to java server side programming WROX press
    for clear description of using request dispatch object