DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

  1. DZone
  2. Data Engineering
  3. Data
  4. Introduction to the Servlet Dispatcher

Introduction to the Servlet Dispatcher

Want to learn more about the servlet dispatcher?

By 
Hitanshi Mehta user avatar
Hitanshi Mehta
·
Updated Aug. 01, 19 · Presentation
Likes (12)
Comment (0)

Save
Tweet
Share
34.88K Views

Join the DZone community and get the full member experience.

Join For Free

The servlet dispatcher allows a request to travel from one servlet to other servlets. An alternative for the request dispatcher is 'send redirect'. For every new request send redirect comes back to the network. However, a request dispatcher occurs within a network(server).

Example

Servlet Dispatcher

Let's understand the concept of the request dispatcher with a simple example. Consider the scenario where we have three servlets, each named servlet1, servlet2, and servlet3. In case we don’t use the dispatcher, whenever we request servlet1, the server passes control to servlet1. After that, if we request servlet2, then control comes back from servlet 1 to server and from the server, control is passed to servlet2. A server might be in India and a servlet might be requested from America. In this case, for a second request, it must come back to the server (India) and go back to the servlet (America). This option is not good if we have heavy traffic in between each request and response. A solution to this problem is to use the dispatcher.

Servlet Dispatcher1

In the same case, if we use dispatcher, then the control passed from servlet1 to servlet2 without coming back to the server and without involving a network. This concept is also known as servlet chaining. It is known as servlet chaining because we are creating a chain of a servlet — from servlet1 to servlet2, servlet2 to servlet3, etc., and at the end, the server will get data from the last servlet.

Data Passing

In servlet chaining with control, data also travel from one servlet to other servlets. This is a major advantage compared to 'send redirect'. In send redirect, every request is a new request, every time you get new data.

Consider that servlet1 has some request parameter that is required by servlet3. In this case, data can travel from servlet1 to servlet2, and after that, from servlet2 to servlet3. So here, we are preserving the request from one servlet to other servlets.

Life of the request is very small. As soon as we get a response, the request is over. In the servlet dispatcher, the life of the request can be preserved from one servlet to another servlet. Because of this, we can divide the task into multiple servlets.

Disadvantages

Most of the time, a dispatcher is efficient, but in the case of large amounts of data, low trafficking, or if we don’t need data at all, we send redirect work.

Types of Dispatcher

    1) Include
    2) Forward

1) Include Dispatcher

Image title

Calling servlet includes any data from the called servlet. It is like a method call where the calling method gains data from the called method. In the case of two servlets, servlet1 will include the response of servlet2 and servlet1 is reverted back to the client. Servlet2 will be called only to get response data.

Let us create a small example of the include dispatcher to better understand the basic concept.

Step 1

Image title


Step 2

Image title

Create a Java web application.

Step 3

Servlet Dispatcher In Java


Provide a project name and set the location of a project where you want it saved.

Step 4

You can select any server.

Image title

Step 5

Image title


Create a servlet.

Step 6

Image title

Provide a servlet name and package name.  

Step 7

Image title


By checking Add information to deployment, the descriptor will register servlet in the web.xml file.

After creating the include servlet, add the following code between the body in IncludeServlet.

1
import java.io.IOException;  
2
import java.io.PrintWriter;  
3
import javax.servlet.RequestDispatcher;  
4
import javax.servlet.ServletException;  
5
import javax.servlet.http.HttpServlet;  
6
import javax.servlet.http.HttpServletRequest;  
7
import javax.servlet.http.HttpServletResponse;  
8
public class IncludeServlet extends HttpServlet {  
9
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)  
10
    throws ServletException, IOException {  
11
    response.setContentType("text/html;charset=UTF-8");  
12
    try (PrintWriter out = response.getWriter()) {  
13
      out.println("<!DOCTYPE html>");  
14
      out.println("<html>");  
15
      out.println("<head>");  
16
      out.println("<title>Servlet IncludeServlet</title>");  
17
      out.println("</head>");  
18
      out.println("<body>");  
19
      out.println("<h1>Servlet IncludeServlet at " + request.getContextPath() + "</h1>");  
20
      request.setAttribute("command", "As commanded by IncludeServlet");  
21
      RequestDispatcher dis = this.getServletContext().getRequestDispatcher("/IncludedServlet");  
22
      dis.include(request, response);  
23
      out.println("<h1>After Include</h1>");  
24
      out.println("</body>");  
25
      out.println("</html>");  
26
    }  
27
  }    
28
} 


Explanation

We have created a command attribute that can travel from one servlet to other servlets. An instance of RequestDispatcher (right-click on RequestDispatcher and select fix imports — this will add the necessary namespace) specify servlet name that's the response we want to add in servlet. With the help of the request.include(request, response), we have specified the type of request dispatcher. After executing the included servlet, the response will come back to include servlet. So, it prints a message 'After Include'.

Create the Included Servlet 

After we create the included servlet, add following code:

15
1
import java.io.IOException;  
2
import java.io.PrintWriter;  
3
import javax.servlet.ServletException;  
4
import javax.servlet.http.HttpServlet;  
5
import javax.servlet.http.HttpServletRequest;  
6
import javax.servlet.http.HttpServletResponse;  
7
public class IncludedServlet extends HttpServlet {  
8
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)  
9
    throws ServletException, IOException {  
10
    response.setContentType("text/html;charset=UTF-8");  
11
    PrintWriter out = response.getWriter();  
12
    out.println("<h1> " + request.getAttribute("command") + " Included Servlet is sending its response</h1>");  
13
    out.println("<h1>This message will be included.</h1>");  
14
  }    
15
}  


Request.include  will add an entire code from the include servlet to the included servlet. We have removed HTML code from an included servlet. Otherwise, it will result in two time HTML code in the included servlet.

Output

Servlet Dispatcher In Java


Output has the response of include servlet and included servlet.

2) Forward Dispatcher

Image title

In the forward dispatcher, servlet1 forwarded whatever data it has to servlet2, and the client gets a response from Servlet2.

Create ForwardServlet

Add the following three lines of code between the body in ForwardServlet.

28
1
import java.io.IOException;  
2
import java.io.PrintWriter;  
3
import javax.servlet.RequestDispatcher;  
4
import javax.servlet.ServletException;  
5
import javax.servlet.http.HttpServlet;  
6
import javax.servlet.http.HttpServletRequest;  
7
import javax.servlet.http.HttpServletResponse;  
8
public class ForwardServlet extends HttpServlet {  
9
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)  
10
    throws ServletException, IOException {  
11
    response.setContentType("text/html;charset=UTF-8");  
12
    try (PrintWriter out = response.getWriter()) {  
13
      out.println("<!DOCTYPE html>");  
14
      out.println("<html>");  
15
      out.println("<head>");  
16
      out.println("<title>Servlet ForwardServlet</title>");  
17
      out.println("</head>");  
18
      out.println("<body>");  
19
      out.println("<h1>Servlet ForwardServlet at " + request.getContextPath() + "</h1>");  
20
      request.setAttribute("forward", "As commanded by ForwardServlet");  
21
      RequestDispatcher dis = this.getServletContext().getRequestDispatcher("/ForwardedServlet");  
22
      dis.forward(request, response);  
23
      out.println("<h1>This message should not come.</h1>");  
24
      out.println("</body>");  
25
      out.println("</html>");  
26
    }  
27
  }  
28
}  


As in the forward servlet, a response will be sent to a forwarded servlet. Anything after dis.forward(request, response) will not be executed.

Create ForwardedServlet

25
1
import java.io.IOException;  
2
import java.io.PrintWriter;  
3
import javax.servlet.ServletException;  
4
import javax.servlet.http.HttpServlet;  
5
import javax.servlet.http.HttpServletRequest;  
6
import javax.servlet.http.HttpServletResponse;  
7
public class ForwardedServlet extends HttpServlet {  
8
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)  
9
    throws ServletException, IOException {  
10
        response.setContentType("text/html;charset=UTF-8");  
11
        PrintWriter out = response.getWriter();  
12
        /* TODO output your page here. You may use following sample code. */  
13
        out.println("<!DOCTYPE html>");  
14
        out.println("<html>");  
15
        out.println("<head>");  
16
        out.println("<title>Servlet ForwardedServlet</title>");  
17
        out.println("</head>");  
18
        out.println("<body>");  
19
        out.println("<h1>Servlet ForwardedServlet at " + request.getContextPath() + "</h1>");  
20
        out.println("<h1> " + request.getAttribute("forward") + " Forwarded Servlet is sending its response</h1>");  
21
        out.println("<h1> After Forwarded");  
22
        out.println("</body>");  
23
        out.println("</html>");  
24
    }   
25
}


Output

Servlet Dispatcher

 
Hope you enjoyed! If you have any comments or questions, please feel free to ask in the comments section! 

Requests Data (computing)

Opinions expressed by DZone contributors are their own.

Partner Resources

×

    July 15, 2019 Daily Digest

  • Most Common Security Fails (Part 2)

  • A Look at Java Optionals

  • Best PHP Frameworks (2019)

  • Introduction to the Servlet Dispatcher

  • How Not to Get Eaten by Technology

  • Dialogflow vs. Lex vs. Watson vs. Wit vs. Azure Bot

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!