SSI - Servlet Chaining
SSI - Servlet Chaining
Server-Side Includes (SSI) is a technology used in web servers to dynamically include content from
one web resource into another before sending it to the client. In the context of Servlets and JSP
(JavaServer Pages), RequestDispatcher is typically used to implement this behavior. SSI allows
a server to include additional dynamic or static content into a response.
RequestDispatcher rd = request.getRequestDispatcher("/header.html");
rd.include(request, response);
In this example, the content of header.html is included in the response generated by the servlet.
The control returns to the servlet after the inclusion, and it continues processing the rest of the
response.
Key Points:
SSI in servlets is often used to include reusable elements like headers, footers, or navigation bars.
The included resource can modify the response, but it cannot set headers or the status code (only
the original servlet can do that).
After including the resource, the control is returned to the original servlet.
Example:
Header.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<header>
<h2>Welcome to My Website</h2>
<nav>
<a href="#">Home</a> |
<a href="#">About</a> |
<a href="#">Contact</a>
</nav>
</header>
footer.html
</body> </html>
MainServlet.java
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/MainServlet")
response.setContentType("text/html");
RequestDispatcher rd = request.getRequestDispatcher("/header.html");
rd.include(request, response);
footerRd.include(request, response);
doGet(request, response);
} }
We use RequestDispatcher rd =
request.getRequestDispatcher("/header.html"); to obtain a dispatcher to the
header.html file.
The include(request, response) method is called to include the content of
header.html into the servlet’s response. The content of header.html is inserted before
the servlet’s main response.
After including the header, the servlet continues generating its own content (<h1> and <p>
in this example).
Footer (Optional):
Request Forwarding is a way to forward the request from one servlet (or JSP) to another resource
(like another servlet, JSP, or HTML file) on the server without the client knowing about the internal
forwarding. This is also done using the RequestDispatcher object, but with the forward()
method instead of include().
How it works:
o A servlet may decide that it doesn't want to generate the complete response itself
and instead forwards the request to another resource.
o Once the request is forwarded, the original servlet does not generate any further
content; the forwarded resource takes over completely.
RequestDispatcher rd = request.getRequestDispatcher("/anotherServlet");
rd.forward(request, response);
In this case, the request is forwarded to anotherServlet, and the original servlet does not generate
any further content. The response to the client is solely generated by anotherServlet.
Key Points:
When forwarding a request, the browser (client) is unaware of the internal forwarding, as the URL
in the browser does not change.
You can forward to resources that are part of the same web application.
The response buffer is cleared when a forward happens, meaning anything written before the
forward is discarded.
After forwarding, control does not return to the original servlet; the forwarded resource handles
the response entirely.
Example:
Request forwarding is done using the RequestDispatcher interface and its forward() method.
If the login is successful, the request is forwarded to the WelcomeServlet, otherwise, the
response can be redirected to an error page.
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// Simple logic to check username and password (in a real-world app, you'd check a database)
if ("admin".equals(username) && "password123".equals(password)) {
// Forward the request to WelcomeServlet
RequestDispatcher rd = request.getRequestDispatcher("/WelcomeServlet");
rd.forward(request, response);
} else {
// If login fails, forward to an error page (error.jsp)
RequestDispatcher rd = request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}
}
}
WelcomeServlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
oginServlet.java:
Request Handling:
o In this servlet, we get the username and password from the HttpServletRequest
object.
o A simple condition is used to check whether the login is successful (username: "admin" and
password: "password123").
Forwarding the Request:
o If the login credentials are valid, the request is forwarded to the WelcomeServlet using
RequestDispatcher.forward().
o If the credentials are invalid, the request is forwarded to an error.jsp page using the
same method.
WelcomeServlet.java:
This servlet handles the forwarded request when the login is successful.
It simply displays a welcome message to the user.
Since the request is forwarded, the URL in the browser will still show the LoginServlet, but the
content is generated by WelcomeServlet
Summary of Differences:
Servlet chaining refers to the process where multiple servlets are invoked one after another in a
sequence to handle a single request. Each servlet performs some processing and forwards the
request to the next servlet in the chain. The final servlet in the chain produces the complete response
that is sent back to the client.
This can be achieved using request forwarding in Java servlets. One servlet can process part of
the request, then forward it to another servlet for further processing, and so on.
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
SecondServlet.java
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/SecondServlet")
public class SecondServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
FinalServlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/FinalServlet")
public class FinalServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
1. FirstServlet:
o Adds an attribute ("message") to the HttpServletRequest object with the value
"Hello from FirstServlet".
o Forwards the request to the SecondServlet using RequestDispatcher.
2. SecondServlet:
o Reads the "message" attribute from the request.
o Modifies the message by appending ", modified by SecondServlet" to it.
o Forwards the request to the FinalServlet.
3. FinalServlet:
o Retrieves the modified message from the request.
o Generates the final response by displaying the message on a webpage.
Output:
Servlet chaining is useful for scenarios where multiple servlets need to collaborate to produce a
response or handle complex processing stages in a modular manner.
In a web application, servlets often need to interact with a database to handle tasks like fetching or
storing user data. This can be achieved using JDBC (Java Database Connectivity), which provides
APIs for connecting and executing SQL queries on a relational database.
Imagine a simple scenario where we want to display a list of users stored in a MySQL database.
We'll create a servlet that connects to the database using JDBC, fetches the user data, and displays
it in the browser.
Steps:
1. Set up a MySQL database with a table to store user information.
2. Use JDBC in the servlet to connect to the database, execute a query, and fetch data.
3. Display the fetched data in the servlet's response.
1. Database Setup:
USE userdb;
2. JDBC Configuration:
Below is a simple servlet that connects to the userdb database, fetches the list of users, and
displays them.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// HTML structure
out.println("<html><body>");
out.println("<h1>User List</h1>");
try {
// Load the MySQL JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace(out);
}
out.println("</body></html>");
}
JDBC URL, Username, Password: These are the connection parameters for connecting to the
MySQL database. Replace them with your own MySQL database credentials.
HTML Output:
The servlet generates a simple HTML page containing a table with the user data fetched from the
database.
5. Output:
<html>
<body>
<h1>User List</h1>
<table border='1'>
<tr><th>ID</th><th>Name</th><th>Email</th></tr>
<tr><td>1</td><td>Alice</td><td>[email protected]</td></tr>
<tr><td>2</td><td>Bob</td><td>[email protected]</td></tr>
</table>
</body>
</html>
Make sure to include the MySQL JDBC driver (mysql-connector-java.jar) in your project’s
classpath
7. Key Points:
JDBC API: Used to connect to the database, execute SQL queries, and retrieve the results.
Servlet: Acts as the controller that processes the request, interacts with the database, and
generates the response.
Database Interaction: The servlet fetches data from a MySQL database and displays it as part of
the servlet's response.
This example is a simple demonstration of how to integrate servlets with JDBC to display
database data in a web application. You can extend this to perform other database operations like
inserting, updating, or deleting records based on user input.