A
A
Arthur Braver2016-01-26 08:21:04
Java
Arthur Braver, 2016-01-26 08:21:04

Explain the use of the RequestDispatcher interface in JAVA?

Good afternoon! There was a question about the RequestDispatcher interface! This interface allows you to redirect requests from the receiving servlet to some other one! Code example:

String param = request.getParameter("param");
if(param.equals("enter")){
    RequestDispatcher rD = request.getServletContext("/AnotherServlet");
    rD.forward(request,response);
}

The line (rD.forward(request,response);) how can it be called if it is a method from the interface and this method is not implemented?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene, 2016-01-26
@zolt85

If the forward method is declared in the RequestDispatcher interface, it can already be called. If the object returned by the request.getServletContext method implements the RequestDispatcher interface, then it has some kind of implementation. Another question is whether this implementation does what you want it to do.

B
bromzh, 2016-01-26
@bromzh

https://ideone.com/6wVcrt

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
  static interface Foo {
    public void foo();
  }
  static class Bar implements Foo {
    @Override
    public void foo() {
      System.out.println("Bar");
    }
  }
  static class Qux implements Foo {
    @Override
    public void foo() {
      System.out.println("Qux");
    }
  }
  public static void main (String[] args) throws java.lang.Exception
  {
    Foo bar = new Bar();
    Foo qux = new Qux();
    bar.foo();
    qux.foo();
  }
}

More or less like this. Only you do not have a constructor, but a method that will return an instance of some class that implements the RequestDispatcher interface. The implementation can be found in different ways. Sometimes the application server substitutes its own, sometimes you need to set up some kind of factory, sometimes the implementation is injected as a dependency, sometimes they use an anonymous class to implement the interface in place.
In Idea, if you hold down ctrl and click on the word "RequestDispatcher", you will jump to the definition of this interface. To the left of the line with the beginning of the interface, there will most likely be a "down" arrow. If you click, then Idea will show all available implementations of this interface (although this is not always possible).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question