RequestDispatcher is an interface provided by the javax.servlet package. It allows one servlet to dispatch a request to another resource on the server. Using RequestDispatcher, a servlet can:
- Forward a request to another resource
- Include another resource’s response in its own response
- target resource can be: servlet, JSP file, or static HTML file.
Why Use RequestDispatcher?
- To separate business logic and presentation
- To enable request chaining
- To reuse resources such as headers, footers, or common JSPs
- To perform server-side navigation without changing the browser URL
How to Obtain a RequestDispatcher Object
There are three ways to obtain a RequestDispatcher instance:
1. Using ServletContext.getRequestDispatcher()
RequestDispatcher rd = getServletContext().getRequestDispatcher(String path);
Explanation:
- Obtained using ServletContext
- The path must be absolute (starts with /)
- Used when the target resource is known at the application level
2. Using ServletContext.getNamedDispatcher()
RequestDispatcher rd = getServletContext().getNamedDispatcher(String name);
Explanation:
- Fetches the dispatcher using the servlet name
- Useful when the servlet is mapped by name rather than URL pattern
3. Using HttpServletRequest.getRequestDispatcher()
RequestDispatcher rd = request.getRequestDispatcher(String path);
Explanation:
- Most commonly used method
- The path can be relative to the current servlet
- Convenient for request-based navigation
Methods of RequestDispatcher
The RequestDispatcher interface provides two methods:
1. forward()
Syntax:
void forward(ServletRequest request, ServletResponse response)
throws ServletException, IOException;
Purpose:
- Forwards the request entirely to another server resource without returning control.
- Browser URL remains unchanged as processing is server-side.
- Uses the same request and response objects and must be called before response commitment.
Example:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GFG extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response) {
try {
RequestDispatcher rd =
request.getRequestDispatcher("targetServlet");
rd.forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Note: The above code will not run in online IDE this is server-side code.
Explanation:
- The servlet receives an HTTP POST request and processes it inside the doPost() method.
- request.getRequestDispatcher("targetServlet") obtains a RequestDispatcher object for the specified target resource within the same server.
- rd.forward(request, response) forwards the request and response to the target servlet, transferring control completely to it without changing the browser URL.
- The try-catch block is used to handle possible exceptions such as ServletException or IOException during request forwarding.
2. include()
Syntax:
void include(ServletRequest request, ServletResponse response)
throws ServletException, IOException;
Purpose:
- Includes the output of another resource in the current response and then returns control to the calling servlet.
- Combines responses from multiple resources, making it useful for reusable components like headers and footers.
- Sets the dispatcher type to INCLUDE, indicating partial response inclusion.
Example:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GFG extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response) {
try {
RequestDispatcher rd =
request.getRequestDispatcher("header.jsp");
rd.include(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Note: The above code will not run in online IDE this is server-side code.
Explanation:
- The servlet handles an HTTP POST request inside the doPost() method.
- request.getRequestDispatcher("header.jsp") creates a RequestDispatcher object that points to the header.jsp resource.
- rd.include(request, response) includes the output of header.jsp in the current servlet’s response instead of transferring control completely.
- After inclusion, execution continues in the same servlet, and the browser URL remains unchanged.
Step-by-Step Implementation Login Validation Using RequestDispatcher
A simple Login Application where:
- User submits username and password
- Servlet validates credentials
- If valid : forward to Welcome page
- If invalid : include error message and reload login page
Step 1: Create a Dynamic Web Project
- Open Eclipse
- File -> New -> Dynamic Web Project
- Project Name: LoginApp
- Finish
Step 2: Configure Target Runtime (Tomcat)
- Select Apache Tomcat
- Apply and close
Step 3: Verify Project Structure
Ensure the project contains src, WebContent, and WEB-INF folders for Java classes and web resources.
Step 4: Create login.jsp
Create a JSP page to collect username and password from the user.
<html>
<body>
<h2>Login</h2>
<form action="login" method="post">
Username: <input type="text" name="username"><br><br>
Password: <input type="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
This JSP page takes login input from the user and sends it to the servlet.
Step 5: Create LoginServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String user = request.getParameter("username");
String pass = request.getParameter("password");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (user.equals("admin") && pass.equals("admin123")) {
RequestDispatcher rd = request.getRequestDispatcher("welcome.jsp");
rd.forward(request, response);
} else {
out.println("<p style='color:red'>Invalid Credentials</p>");
RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
rd.include(request, response);
}
}
}
This servlet validates credentials and uses forward() or include() accordingly.
Step 6: Create welcome.jsp
Create a JSP page to display a success message after successful login.
<html>
<body>
<h2>Welcome! Login Successful</h2>
</body>
</html>
This JSP page is displayed only when login is successful.
Step 7: Configure web.xml
Map the servlet with a URL pattern in the deployment descriptor.
<web-app>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
This file links the servlet class with the request URL.
Step 8: Deploy Project on Server
- Run project on Tomcat
- Start server
Step 9: Access Application in Browser
Open the application using the URL:
http://localhost:8080/ProjectName/login.jsp
This loads the login page for user interaction.
Step 10: Test Valid Credentials
Enter correct credentials (admin / admin123) and submit the form. Valid credentials forward the request to welcome.jsp.
Step 11: Test Invalid Credentials
Enter incorrect credentials and submit the form. Invalid credentials include login.jsp again with an error message.
Forward vs Include
Feature | forward() | include() |
|---|---|---|
Transfers control | Yes | No |
Client aware | No | No |
Response content | Replaced | Appended |
Execution returns | No | Yes |
Dispatcher type | FORWARD | INCLUDE |