Key Servlet Techniques     // practical
Peter Komisar © Conestoga College version 1.1

We will finish off our survey of JSPs next lecture, but first we
need to introduce a key technique introduced in the Sevlet 2.2
API associated with the class, RequestDispatcher.

The following servlet was found at the Java2s web site that
examples the ideas associated with the use of the
RequestDispatcher quite nicely.

RequestDispatcher Sample
from the Java2s web site,
http://www.java2s.com/Tutorial/Java/0400__Servlet/ServletControllerDispatcher.htm

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class J2Servlet extends HttpServlet {
    public void doGet(HttpServletRequest request,
        HttpServletResponse response)
         throws ServletException, java.io.IOException {

        RequestDispatcher dispatcher = null;
        String param = request.getParameter("go");
             if (param == null)
                 throw new
                     ServletException("Missing parameter in Controller.");
             else if (param.equals("weather"))
                 dispatcher = getServletContext( ).
                     getNamedDispatcher("Weather");
             else if (param.equals("maps"))
                 dispatcher = getServletContext( ).
                     getNamedDispatcher("Maps");
            else
                throw new ServletException(
                    "Improper parameter passed to Controller.");
         /*check for a null dispatcher, then
            dispatch the request to the correct URL*/
        if (dispatcher != null)
            dispatcher.forward(request,response);
        else
            throw new ServletException(
              "Controller received a null dispatcher.");
    }
}

getNamedDispatcher( )

There is a method that is called  somewhat magically
called getNamedDispatcher( ). The method is found in
the ServletContext class which refers to the container
that the Servlet runs in.

(The ServletContext object is contained within the
ServletConfig object, which the Web server provides
the servlet when the servlet is initialized. We get a
handle to it via the getServletContext( ) method.

The getNamedDispatcher( ) method returns a RequestDispatcher
object which 'acts as a wrapper' for the so named servlet.
(Alternativily, naming may also be executed via the web app
deployment descriptor.)


forward( )


The forward method is then called on the RequestDispatcher
to direct the request to the appropriate object. Note it takes
the same parameters as a Servlet's doGet( ) or doPost( )
method, a request and a response.

Following is an HTML page and Servlets that can be used in
conjunction with the above servlet.

HTML Page with Form

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<TITLE>Hello Form</TITLE>
</HEAD>
<BODY>
<H2>Hello!</H2>
<HR/>
<FORM METHOD=GET ACTION="J2Servlet">
Hello! Do you want the Weather or a Map?
(type weather or maps)
<INPUT TYPE=TEXT NAME="go" INPUT TYPE=SUBMIT/>
</FORM>


Maps Servlet

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Maps
 */
public class Maps extends HttpServlet {
    private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Maps() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    //    super.doGet(request, response);
       
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Maps Page </title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Find A Map!</h1>");
        out.println("<HBr/>");
        out.println("Earth or Extra-Terrestrial?");
        out.println("</body>");
        out.println("</html>");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doPost(request, response);
    }
}

Weather Servlet

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Weather
 */
public class Weather extends HttpServlet {
    private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Weather() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        // super.doGet(request, response);
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Weather Page! </title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Today's Weather!</h1>");
        out.println("<HBr/>");
        out.println("Terrestrial or Sub-terrestrial?");
        out.println("</body>");
        out.println("</html>");
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doPost(request, response);
    }
}

Forwarding to a JSP

The only difference between forwarding to a JSP and
forwarding to a servlet is that the forward slash representing
the relative root context needs to be included before the
JSP's String literal. Following is a form convention that
seems to be used frequently that describes what is
happening next.  The above code is adapted to create
the following suite of web components which can be loaded
into Eclipse and run from the starting HTML page.


Example

String nextJSP = "/Locations.jsp";
   RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
   dispatcher.forward(request,response);

Following is another example, with a few more targets,
this time in the form of JSPs.

Going.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<H1>Routes</H1>
<FORM METHOD=GET ACTION="ToJSP">
Hello! location or route
<INPUT TYPE=TEXT NAME="go"><P>
<INPUT TYPE=SUBMIT>
</FORM>
</body>
</html>



ToJSP Servlet

import javax.servlet.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ToJSP
 */
public class ToJSP extends HttpServlet {
    private static final long serialVersionUID = 1L;
   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ToJSP() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        // super.doGet(request, response);
        RequestDispatcher dispatcher=null;
         String param = request.getParameter("go");
         if (param == null)
            throw new
              ServletException("No Parameters!");
        
        else if (param.equals("location")){
        String  nextJSP = "/Locations.jsp";
         dispatcher =
            getServletContext().getRequestDispatcher(nextJSP);
        dispatcher.forward(request,response);
        }
         else if (param.equals("route")){
          String nextJSP = "/Routes.jsp";
          dispatcher = getServletContext().getRequestDispatcher(nextJSP);
         dispatcher.forward(request,response);
         }
       
     else throw new ServletException("Servlet Exception");
         }
            /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost
   (HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
               super.doPost(request, response);
    }
}

Location JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Looking for a Location?</h1>
</body>
</html>

Routes JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Routes JSP </title>
</head>
<body>
<H1>Pick a Route!</H1>

</body>
</html>


Exercise


1 ) Using Eclipse, create a JSP that forwards to four other
JSPs each representing a Season or a direction. You may
base this on whether a random number is returned between
0, .33, .33 and .66, and .66 and 1.


2) Create a Servlet that dispatches it's request to three other
servlets based on a parameter passed from an HTML page
with a form and submit button.  An example might be ice,
water and vapour. The servlets will return a statement about
each phase.

// or pick your own parameters and topics

3) Create a servlet that dispatches it's request to three JSP
   pages based on a parameter passed from an HTML page
  as in Q.2.