O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.1. Including a Resource Each Time a Servlet Handles a Request

Problem

You want to include information from an external file in a servlet each time the servlet handles a request.

Solution

Use the javax.servlet.RequestDispatcher.include(request,response) method in the doGet( ) method of the servlet that includes the external file.

Discussion

Including the content in the javax.servlet.http.HttpServlet's doGet( ) method initiates the include mechanism whenever the web container receives a GET request for the servlet.

Tip

When using this design, implement the servlet's doPost( ) method to call doGet(request,response).

Example 6-1 shows a servlet that imports a copyright template in the doGet( ) method using the javax.servlet.RequestDispatcher.include( ) method.

Example 6-1. Including content in the HttpServlet's init( ) method

package com.jspservletcookbook;           

import javax.servlet.*;
import javax.servlet.http.*;

public class IncludeServlet extends HttpServlet {
    
 public void doGet(HttpServletRequest request, 
   HttpServletResponse response) throws ServletException,
   java.io.IOException {
        
        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter( );
        
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Include Servlet</title>");  
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Welcome To Our Universe</h1>");
        out.println("Imagine the rest of the page here.<br><br>");
        //Include the copyright informationRequestDispatcher dispatcher = request.getRequestDispatcher( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required