Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Understanding Servlet Include Forwarding Mechanism

Notes 3

The include forwarding process in Java Servlets operates as follows:

  1. If the target resource is a Servlet or JSP, their respective service() method is invoked. The response content generated by this method is appended to the response body of the originating Servlet. If the target is an HTML document, its content is directly added to the originating Servlet's response.
  2. Control returns to the service method of the originating Servlet, allowing subsequent code blocks to execute.

Characteristics of Include Forwarding

Compared to the forward() method, the include() method exhibits these distinct behaviors:

  1. Output data from both the source Servlet and the included target resource are combined into the final response.
  2. Any modifications made to the response status code or headers with in the target resource are ignored by the container.

Implementation Example

Source Servlet (DispatcherServlet.java)

package com.example.web;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(urlPatterns = "/dispatcher")
public class DispatcherServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        System.out.println("DispatcherServlet processing request");
        String paymentAmount = request.getParameter("amount");
        System.out.println("Payment amount: " + paymentAmount);
        
        // Response configuration can be set before or after include
        // response.setContentType("text/html;charset=UTF-8");
        
        // Obtain request dispatcher for target resource
        RequestDispatcher dispatcher = request.getRequestDispatcher("processor");
        // Alternative targets:
        // request.getRequestDispatcher("data.html");
        // request.getRequestDispatcher("result.jsp");
        // request.getRequestDispatcher("WEB-INF/template.html");
        
        // Include target resource response
        dispatcher.include(request, response);
        
        // Continue adding response content after inclusion
        response.getWriter().println("\nAdditional content from DispatcherServlet");
        
        /*
         * Key points about include forwarding:
         * 1. Server-side operation, transparent to browser
         * 2. Browser address bar remains unchanged
         * 3. Request parameters propagate to target resource
         * 4. Same request/response objects are shared
         * 5. Enables content aggregation from multiple resources
         * 6. Can access resources under WEB-INF directory
         * 7. Limited to internal application resources
         */
    }
}

Target Servlet (PaymentProcessor.java)

package com.example.web;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/processor")
public class PaymentProcessor extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        System.out.println("PaymentProcessor executing");
        String paymentAmount = request.getParameter("amount");
        System.out.println("Processing amount: " + paymentAmount);
        
        // Generate response content
        PrintWriter out = response.getWriter();
        out.println("Payment processed successfully: $" + paymentAmount);
        
        // Note: Header modifications here are typically ignored
        // response.setStatus(HttpServletResponse.SC_ACCEPTED);
    }
}
Tags: Java Servlet

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Deploying a Maven Web Application to Tomcat 9 Using the Tomcat Manager

Tomcat 9 does not provide a dedicated Maven plugin. The Tomcat Manager interface, however, is backward-compatible, so the Tomcat 7 Maven Plugin can be used to deploy to Tomcat 9. This guide shows two...

Skipping Errors in MySQL Asynchronous Replication

When a replica halts because the SQL thread encounters an error, you can resume replication by skipping the problematic event(s). Two common approaches are available. Methods to Skip Errors 1) Skip a...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.