Jenna 009

Jenna 009

1562985684

What is Servlet Dispatcher

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

Example 

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 and 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 using the dispatcher.

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 a redirect. In sending a 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, life of the request can be preserved from one servlet to other. Because of this, we can divide the task into multiple servlets.

Disadvantages

Most of the time, 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

Calling the 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

Step 2

Create a Java web application.

Step 3

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

Step 4

You can select any server.

Step 5

Create a servlet.

Step 6

Provide a servlet name and package name. 

Step 7

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.

import java.io.IOException;  
import java.io.PrintWriter;  
import javax.servlet.RequestDispatcher;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
public class IncludeServlet extends HttpServlet {  
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)  
    throws ServletException, IOException {  
    response.setContentType("text/html;charset=UTF-8");  
    try (PrintWriter out = response.getWriter()) {  
      out.println("<!DOCTYPE html>");  
      out.println("<html>");  
      out.println("<head>");  
      out.println("<title>Servlet IncludeServlet</title>");  
      out.println("</head>");  
      out.println("<body>");  
      out.println("<h1>Servlet IncludeServlet at " + request.getContextPath() + "</h1>");  
      request.setAttribute("command", "As commanded by IncludeServlet");  
      RequestDispatcher dis = this.getServletContext().getRequestDispatcher("/IncludedServlet");  
      dis.include(request, response);  
      out.println("<h1>After Include</h1>");  
      out.println("</body>");  
      out.println("</html>");  
    }  
  }    
}

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 include servlet, add following code:

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;  
public class IncludedServlet extends HttpServlet {  
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)  
    throws ServletException, IOException {  
    response.setContentType("text/html;charset=UTF-8");  
    PrintWriter out = response.getWriter();  
    out.println("<h1> " + request.getAttribute("command") + " Included Servlet is sending its response</h1>");  
    out.println("<h1>This message will be included.</h1>");  
  }    
}

Request.include  will add an entire code from the include servlet into the included servlet. So, we have removed HTML code from an included servlet. Otherwise, it will result in two types of HTML code in the included servlet.

Output

Output has the response of include servlet and included servlet.

2) Forward Dispatcher

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.

import java.io.IOException;  
import java.io.PrintWriter;  
import javax.servlet.RequestDispatcher;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
public class ForwardServlet extends HttpServlet {  
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)  
    throws ServletException, IOException {  
    response.setContentType("text/html;charset=UTF-8");  
    try (PrintWriter out = response.getWriter()) {  
      out.println("<!DOCTYPE html>");  
      out.println("<html>");  
      out.println("<head>");  
      out.println("<title>Servlet ForwardServlet</title>");  
      out.println("</head>");  
      out.println("<body>");  
      out.println("<h1>Servlet ForwardServlet at " + request.getContextPath() + "</h1>");  
      request.setAttribute("forward", "As commanded by ForwardServlet");  
      RequestDispatcher dis = this.getServletContext().getRequestDispatcher("/ForwardedServlet");  
      dis.forward(request, response);  
      out.println("<h1>This message should not come.</h1>");  
      out.println("</body>");  
      out.println("</html>");  
    }  
  }  
}

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

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;  
public class ForwardedServlet extends HttpServlet {  
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)  
    throws ServletException, IOException {  
        response.setContentType("text/html;charset=UTF-8");  
        PrintWriter out = response.getWriter();  
        /* TODO output your page here. You may use following sample code. */  
        out.println("<!DOCTYPE html>");  
        out.println("<html>");  
        out.println("<head>");  
        out.println("<title>Servlet ForwardedServlet</title>");  
        out.println("</head>");  
        out.println("<body>");  
        out.println("<h1>Servlet ForwardedServlet at " + request.getContextPath() + "</h1>");  
        out.println("<h1> " + request.getAttribute("forward") + " Forwarded Servlet is sending its response</h1>");  
        out.println("<h1> After Forwarded");  
        out.println("</body>");  
        out.println("</html>");  
    }   
}

Output

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


Originally published on https://dzone.com

#java #web-service #web-development

What is GEEK

Buddha Community

What is Servlet Dispatcher

Add a Servlet Filter in Spring Boot [Video]

Get your Servlet Filter in your Spring Boot application up and running in just over 3 minutes, so you have more time for the rest of your app.

In the video below, we take a closer look at the How to add a Servlet filter in Spring Boot? | Spring Boot: Servlet Filter | Spring Boot tutorial. Let’s get started!

#spring boot #servlet filter #add a servlet filter in spring boot #servlet

Java File Upload Example with Servlet 3.0 API

Java File Upload Example with Servlet 3.0 API

Before Java EE 6, applications usually have to use an external library like Apache’s Common File Upload to handle file upload functionality. Fortunately, developers do no longer have to depend on any external library, since Java EE 6 provides built-in file upload API.Runtime requirement:

  • Java EE 6 with Servlet 3.0.
  • Server: Apache Tomcat 7.0

Of course you can use newer versions of Java EE and Tomcat server.

#java #servlet 3.0 api #api #servlet

Brooke  Giles

Brooke Giles

1606980300

Introduction to Servlets and Servlet Containers

In this tutorial, we’ll understand conceptually what servlets and servlet containers are and how they work.

We’ll also see them in the context of a request, response, session objects, shared variables, and multithreading.

#servlets #programming #developer #java

Murray  Beatty

Murray Beatty

1590990089

Micronaut Servlet - A New Micronaut Project for Servlet API Developers

The specific non-Netty features of Micronaut’s HTTP built-in server should work with the supported servlet containers, namely Tomcat, Jetty and Undertow. Micronaut Servlet includes several extensions to simplify working with the Servlet API. This includes the ability to: receive the traditional Servlet API interfaces, HTTPServletRequest and HttpServletResponse, as method parameters; utilize Micronaut interfaces, Readable and Writable, to simplify servlet read/write operations; and support for multipart forms.

In traditional Servlet API development, it is required to override the methods, doGet(), doPost(), etc., using the HTTPServletRequest and HTTPServletResponse interfaces for handling HTTP verbs within the lifecycle of the servlet application.T

#servlets #java #programming

sophia tondon

sophia tondon

1621340676

Taxi Dispatch Software/ System | White Label Taxi App

Manage your taxi business efficiently with robust** taxi booking and dispatch software. Automate your operations with our smart and innovative solution and improve profitability. 16+ yrs exp, 40+ countries served, 50+ enterprise clients.

#white label taxi app #taxi tracking software #taxi management software #taxi dispatch system #taxi cab dispatch software #taxi booking system