Home  >  Article  >  Java  >  Servlet RequestDispatcher

Servlet RequestDispatcher

WBOY
WBOYOriginal
2024-08-30 15:16:09968browse

The RequestDispatcher interface allows the request to be routed to another resource, which may be HTML, Servlet, or JSP. This interface can also be utilized to incorporate the content of an additional resource. It is one of the servlet cooperation methods. The RequestDispatcher interface is part of the java. Servlet package. Using this interface, the servlet returns an object after receiving a request.

Servlet RequestDispatcher

ADVERTISEMENT Popular Course in this category JAVA SERVLET - Specialization | 18 Course Series | 6 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Overview of Servlet RequestDispatcher

The servlet RequestDispatcher uses a user interface to request one source link to another. The requestdispatcher sends form data to the validation servlet page. If the servlet page validates the information, the request dispatcher forwards the link to another servlet or JSP page using a path or string name. If the web page does not validate information, the request dispatcher object includes HTML or JSP page and shows an error message.

How to Create Servlet RequestDispatcher?

A RequestDispatcher object can send a request to a resource or include it in a response. The resource may be either static or dynamic. There are three ways to create a servlet requestdispatcher on the servlet page. First, we have to use the string name of the path or path of the page.

Method 1

The following syntax shows how to create an object of request dispatcher with a path.

Syntax:

RequestDispatcher requestdispatcherObject = ServletContext.getRequestDispatcher(" String file_path");

Explanation:

  • The public interface a servlet utilises ServletContext to communicate with its servlet container.
  • The path is a string that specifies the resource’s pathname.
  • The resource file format must be either servlet, HTML, or JSP.

Method 2

The following syntax shows how to create an object of request dispatcher.

Syntax:

RequestDispatcher requestdispatcherObject = ServletContext.getNamedDispatcher(" String name");

Explanation:

  • The public interface ServletContext defines the collection of methods a servlet uses to communicate with its container.
  • The “name” is a string that specifies the servlet to wrap.

Method 3

The following syntax shows how to create an object of a request dispatcher with a request interface.

Syntax:

RequestDispatcher requestdispatcherObject = request.getRequestDispatcher(" String file_path");

Explanation:

  • The “request” is an object of the type HttpServletRequest.
  • The file_Path is a string that specifies the resource’s pathname. It must be relative to the current servlet.

Methods of Servlet RequestDispatcher

The requestdispatcher has two methods for the servlet and Html pages. This method either forwards or includes the file source to the next source.

  • Forward method
  • Include method

1. Forward Method

If the information validates and the web page is forwarded to the next servlet page, then use the forward method.

Syntax:

The following syntax shows how to use the forward method.

void forward(ServletRequest req, ServletResponse resp) throws ServletException, IOException

Explanation:

  • Modifier/Type: void.
  • This technique redirects a request from a servlet to a different server resource.
  • The method is invoked before the response is transmitted to the client.
  • The procedure will throw an IllegalStateException if the response has already been sent.
  • The request(req) and response(resp) are the identical objects supplied to the service method to the servlet.
  • This function sets the request’s dispatcher type to the “DispatcherType.FORWARD”.

Example:

Code:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Register extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter printout = resp.getWriter();
String first_id = req.getParameter("fn");
RequestDispatcher rdispatcher = req.getRequestDispatcher("/index.html");
rdispatcher.include(req, resp);
}
}

2. Include method

If the information does not validate, then the page includes the same page with an error message.

Syntax:

The following syntax shows how to use the include method.

void include(ServletRequest req, ServletResponse resp) throws ServletException, IOException

Explanation:

  • Modifier/Type: void
  • The request(req) and response(resp) are the identical objects supplied to the service method to the servlet.
  • This technique is used to include the response of a resource into the current servlet response.
  • This function sets the request’s dispatcher type to the “DispatcherType.INCLUDE”.

Example:

Code:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Register extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter printout = resp.getWriter();
String first_id = req.getParameter("fn");
printout.print("Sorry!! Wrong UserId!");
RequestDispatcher rdispatcher = req.getRequestDispatcher("/index.html");
rdispatcher.include(req, resp);
}
}

Servlet RequestDispatcher Interface

The servlet requestdispatcher requires the following four files:

  • Index.html: Insert the information in the form.
  • Register.java: Use the servlet requestdispatcher interface with the method.
  • FinalServlet.java: Use the servlet page for the final output.
  • Web.xml: A deployment descriptor file that contains the information about the servlet. A deployment descriptor file that contains the information about the servlet.

index.html: create the required form

Code:

<!DOCTYPE html>
<html>
<head>
<title> Basic form </title>
</head>
<body>
<form action = "first_servlet" method = "post">
<label for = "fn"> User Id: </label>
<input type = "text" id = "fn" name = "fn"><br><br>
<label for = "ln"> First name: </label>
<input type = "text" id = "ln" name = "ln"><br>
<input type = "submit" value = "Submit">
</form>
</body>
</html>

Register.java: create the first servlet with a request dispatcher interface

Code:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Register extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter printout = resp.getWriter();
String first_id = req.getParameter("fn");
String first_name = req.getParameter("ln");
if(first_id.equals("servlet"){
RequestDispatcher rdispatcher = req.getRequestDispatcher("sec_servlet");
rdispatcher.forward(req, resp);
}
else{
printout.print("Sorry!! Wrong UserId!");
RequestDispatcher rdispatcher = req.getRequestDispatcher("/index.html");
rdispatcher.include(req, resp);
}
}
}

FinalServlet.java: create a second servlet page for the required output

Code:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FinalServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter printout = resp.getWriter();
String name = req.getParameter("ln");
printout.print("Welcome "+name);
}
}

Web.xml: create servlet parameters with its page

Code:

<web-app>
<servlet>
<servlet-name> Register </servlet-name>
<servlet-class> Register </servlet-class>
</servlet>
<servlet>
<servlet-name> FinalServlet </servlet-name>
<servlet-class> FinalServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> Register </servlet-name>
<url-pattern> /first_servlet </url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name> FinalServlet </servlet-name>
<url-pattern> /sec_servlet </url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file> index.html </welcome-file>
</welcome-file-list>
</web-app>

Output 1: form page

Servlet RequestDispatcher

Output 2: servlet page output with an error message

Servlet RequestDispatcher

Output 2: servlet page final output

Servlet RequestDispatcher

Conclusion

The servlet requestdispatcher interface moves users from one source to another web application source. It is forward and includes the file path per requirement and source output.

The above is the detailed content of Servlet RequestDispatcher. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Frameworks in JavaNext article:Frameworks in Java