Servlet Collaboration
Servlet collaboration allows servlets to interact with each other and share data. This can be done in two primary ways: forwarding a request to another servlet or including content from another servlet in the current response. The two mechanisms for achieving this are RequestDispatcher and sendRedirect.
1. RequestDispatcher
The RequestDispatcher interface is used to forward a request from one servlet to another or to include content from another servlet or JSP. It enables servlet collaboration, allowing one servlet to pass control to another servlet or include content without the client being aware of it.
1.1 Forward
The forward() method of the RequestDispatcher forwards the request to another resource (like a servlet or JSP) on the server. The client does not know about the forwarding process, and the URL in the browser remains unchanged.
RequestDispatcher dispatcher = request.getRequestDispatcher("/anotherServlet");
dispatcher.forward(request, response);
In the example, the request is forwarded to anotherServlet without changing the URL in the browser.
1.2 Include
The include() method of the RequestDispatcher includes content from another resource in the current response. The client receives the combined response, and the URL remains unchanged.
RequestDispatcher dispatcher = request.getRequestDispatcher("/anotherServlet");
dispatcher.include(request, response);
In the example, content from anotherServlet is included in the current response.
2. sendRedirect
The sendRedirect() method of the HttpServletResponse object sends a redirection response to the client. The client is informed of the redirect, and the browser URL changes to the new location. This is a client-side redirection.
response.sendRedirect("http://www.example.com");
In this example, the browser will be redirected to the specified URL, and the URL in the browser will change.
3. forward() vs sendRedirect()
Both forward() and sendRedirect() are used to direct a request to another resource, but they differ in how the redirection happens and their effects on the client.
| Aspect | forward() | sendRedirect() |
|---|---|---|
| Request Handling | Server-side request forwarding | Client-side redirection |
| URL Visibility | URL remains unchanged in the browser | URL changes to the new location in the browser |
| Performance | More efficient (server-side) | Less efficient (client-side) |
| Use Case | When the request must be processed by another servlet or JSP internally | When the client needs to be redirected to a different location (e.g., login page after successful login) |
RequestDispatcher - forward() Example
Login Form
This is a simple login form that will be processed by a servlet. Below is the code to handle the login request:
<!-- Login Form HTML -->
<form action="LoginServlet" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<button type="submit">Login</button>
</form>
LoginServlet Code
This is the Java code for the LoginServlet that processes the login request and forwards the response to the appropriate page:
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 username = request.getParameter("username");
String password = request.getParameter("password");
if ("admin".equals(username) && "admin123".equals(password)) {
<!-- Successful login, forward to welcome page -->
RequestDispatcher dispatcher = request.getRequestDispatcher("welcome.jsp");
dispatcher.forward(request, response);
} else {
<!-- Login failed, forward to error page -->
RequestDispatcher dispatcher = request.getRequestDispatcher("login-error.jsp");
dispatcher.forward(request, response);
}
}
}
Welcome Page (welcome.jsp)
This is the JSP code that is displayed after a successful login:
<%-- Check if the user is logged in --%>
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h2>Welcome, Admin!</h2>
<p>You have successfully logged in.</p>
</body>
</html>
Login Error Page (login-error.jsp)
This is the JSP code that is displayed when the login fails:
<%-- Check for error message --%>
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<title>Login Failed</title>
</head>
<body>
<h2>Login Failed</h2>
<p class="error">Invalid username or password. Please try again.</p>
<a href="login.html">Go back to login page</a>
</body>
</html>
RequestDispatcher - include() Example
The `RequestDispatcher.include()` method is used to include the content of another resource (like a JSP file or servlet) in the response. It’s typically used when you want to include the content of another resource within the current response but without redirecting the user to that resource.
Example Use Case
Let’s say you have a main servlet or JSP that needs to include a footer from a separate JSP file. Below is an example of using `RequestDispatcher.include()` to include the content of a footer JSP in the main page.
Steps:
- Get the `RequestDispatcher` for the resource you want to include.
- Call the `include()` method on the dispatcher.
Code Example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MainServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Set content type
response.setContentType("text/html");
// Get the PrintWriter object to write response
PrintWriter out = response.getWriter();
// Write some content for the main page
out.println("<html>");
out.println("<head><title>Main Page</title></head>");
out.println("<body>");
out.println("<h1>Welcome to the Main Page</h1>");
out.println("<p>Here is the content of the main page.</p>");
// Get the RequestDispatcher for the footer
RequestDispatcher dispatcher = request.getRequestDispatcher("footer.jsp");
// Include the content of the footer.jsp in the response
dispatcher.include(request, response);
out.println("</body>");
out.println("</html>");
}
}
footer.jsp
<%-- footer.jsp --%>
<footer>
<p>This is the footer content.</p>
<p>© 2024 My Website</p>
</footer>
Explanation:
In this example, the `MainServlet` sends content for the main page, including a title and some text. It then uses `RequestDispatcher` to include the content from the `footer.jsp` into the response, such as the footer text. The `include()` method allows us to include the content of the footer without making a separate request or redirecting the user.
When to Use RequestDispatcher Include
You would typically use the `include()` method when:
- You want to include content from another resource in the current response.
- You want to include common elements such as headers, footers, or navigation menus.
- You are working with dynamic content that should be displayed on multiple pages, like a footer or sidebar.
Send Redirect Method Example
The `sendRedirect()` method is used to redirect the user to a different URL. Unlike the `RequestDispatcher`, which forwards the request within the same server, `sendRedirect()` sends a new HTTP request to the browser, which then sends a request to the new URL. This results in a new round-trip to the server.
Example Use Case
In this example, when the user logs in, the servlet will redirect them to a "welcome" page after successful login.
Code Example
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 {
// Get user credentials from request
String username = request.getParameter("username");
String password = request.getParameter("password");
// Simulating a login check
if ("admin".equals(username) && "password".equals(password)) {
// Redirecting to the welcome page upon successful login
response.sendRedirect("welcome.jsp");
} else {
// Redirecting to the login page upon failure
response.sendRedirect("login.jsp");
}
}
}
Explanation:
In this example, the `LoginServlet` checks the provided username and password. If they match the hardcoded credentials ("admin" and "password"), the servlet redirects the user to the "welcome.jsp" page using `response.sendRedirect("welcome.jsp")`. If the credentials are incorrect, the user is redirected back to the "login.jsp" page.
Redirecting to External URLs
You can also use `sendRedirect()` to redirect to an external URL. For example:
response.sendRedirect("https://www.example.com");
Key Points:
- The `sendRedirect()` method sends a new HTTP request to the client’s browser, which then makes a new request to the target URL.
- It can be used to redirect to either an internal resource (another page or servlet) or an external URL.
- After calling `sendRedirect()`, the response is committed, and no further content can be written to the response body.