0% found this document useful (0 votes)
21 views13 pages

SSI - Servlet Chaining

Servlet chaining

Uploaded by

oshanmitkari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views13 pages

SSI - Servlet Chaining

Servlet chaining

Uploaded by

oshanmitkari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

1.

Server-Side Includes (SSI) in Servlet:

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.

 How it works in Servlets:


o A servlet can use a RequestDispatcher to include another resource (like a JSP
page, another servlet, or a static HTML file) in its response.
o The include() method of the RequestDispatcher is used for this purpose.

// Obtain the RequestDispatcher object

RequestDispatcher rd = request.getRequestDispatcher("/header.html");

// Include the content of the resource

rd.include(request, response);

// Continue with the rest of the servlet's response

response.getWriter().println("This is the main content.");

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

<footer> <p>&copy; 2024 My Website. All rights reserved. </p> </footer>

</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")

public class MainServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Set content type

response.setContentType("text/html");

// Obtain the RequestDispatcher for the header.html

RequestDispatcher rd = request.getRequestDispatcher("/header.html");

// Include the content of header.html into the response

rd.include(request, response);

// Write the main content of the servlet response

response.getWriter().println("<h1>Welcome to the Main Content!</h1>");

response.getWriter().println("<p>This is the body of the page, generated by the MainServlet.</p>");

// Include the footer (optional, if you want to add)

RequestDispatcher footerRd = request.getRequestDispatcher("/footer.html");

footerRd.include(request, response);

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

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):

 Another RequestDispatcher can be used to include a footer.html in a similar way as


the header.

2. Request Forwarding in Servlet:

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.

// Obtain the RequestDispatcher object

RequestDispatcher rd = request.getRequestDispatcher("/anotherServlet");

// Forward the request to another resource

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.

Example Use Case:

Imagine you have two servlets:

1. LoginServlet: Handles login verification.


2. WelcomeServlet: Displays a welcome message if the login is successful.

If the login is successful, the request is forwarded to the WelcomeServlet, otherwise, the
response can be redirected to an error page.

1. Servlet Code for Request Forwarding:

LoginServlet.java (Handles login logic and forwards the request)


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("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Get username and password from the request


String username = request.getParameter("username");
String password = request.getParameter("password");

// 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;

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Set content type


response.setContentType("text/html");

// Generate welcome message in the response


response.getWriter().println("<h1>Welcome, you have successfully logged in!</h1>");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
doGet(request, response);
}
}

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 in Java:

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.

How Servlet Chaining Works:

1. A client makes a request to the first servlet in the chain.


2. The first servlet processes the request (e.g., modifies request data, adds attributes, logs, etc.)
and forwards the request to the next servlet.
3. The next servlet further processes the request and forwards it, and this process continues
until the final servlet generates the complete response.

Example of Servlet Chaining:

Let's create a servlet chain with three servlets:

1. FirstServlet: Adds an attribute to the request and forwards it to SecondServlet.


2. SecondServlet: Reads the attribute, modifies it, and forwards the request to FinalServlet.
3. FinalServlet: Reads the modified data and generates the final response.
1. FirstServlet.java (First in the chain)

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;

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Add an attribute to the request object


request.setAttribute("message", "Hello from FirstServlet");

// Forward the request to the SecondServlet


RequestDispatcher rd = request.getRequestDispatcher("/SecondServlet");
rd.forward(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
doGet(request, response);
}
}

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;

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Retrieve and modify the message attribute


String message = (String) request.getAttribute("message");
message += ", modified by SecondServlet";

// Set the modified attribute in the request object


request.setAttribute("message", message);

// Forward the request to the FinalServlet


RequestDispatcher rd = request.getRequestDispatcher("/FinalServlet");
rd.forward(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
doGet(request, response);
}
}

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;

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Retrieve the final message from the request


String finalMessage = (String) request.getAttribute("message");

// Set content type and generate the final response


response.setContentType("text/html");
response.getWriter().println("<h1>" + finalMessage + "</h1>");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
doGet(request, response);
}
}

Explanation of the Code:

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:

When the request is made to FirstServlet (e.g., via


http://localhost:8080/YourApp/FirstServlet), the following will happen:

 FirstServlet adds "Hello from FirstServlet" to the request.


 SecondServlet modifies the message to "Hello from FirstServlet, modified by SecondServlet".
 FinalServlet retrieves the modified message and displays it in the browser.

Final Response in the Browser:


html
Copy code
<h1>Hello from FirstServlet, modified by SecondServlet</h1>

Key Points about Servlet Chaining:

 Request Sharing: The same HttpServletRequest and HttpServletResponse objects are


passed through the chain. This allows data sharing between servlets by setting attributes on the
request.
 No Client Awareness: The client (browser) is unaware of the chaining; the URL remains the same
as the initial servlet.
 Multiple Processing Stages: Each servlet in the chain can perform a specific processing step on the
request, enhancing the modularity and maintainability of the application.
 Final Output: The final response is only generated by the last servlet in the chain, and earlier
servlets in the chain can modify the request as needed.

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.

Servlet with JDBC

Servlet with JDBC (Java Database Connectivity)

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.

Example Use Case:

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:

First, create a database and a table in MySQL.

Create Database and Table:

CREATE DATABASE userdb;

USE userdb;

CREATE TABLE users (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100)
);

-- Insert sample data


INSERT INTO users (name, email) VALUES ('Alice', '[email protected]');
INSERT INTO users (name, email) VALUES ('Bob', '[email protected]');

2. JDBC Configuration:

To interact with MySQL using JDBC, you need to:

1. Download the MySQL JDBC driver (e.g., mysql-connector-java.jar).


2. Add the JDBC driver to your project’s classpath.

3. Servlet Code to Connect to MySQL Database:

Below is a simple servlet that connects to the userdb database, fetches the list of users, and
displays them.

UserServlet.java (Servlet with JDBC)

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;

// JDBC connection parameters


private String jdbcURL = "jdbc:mysql://localhost:3306/userdb";
private String jdbcUsername = "root";
private String jdbcPassword = "your_password"; // Replace with your MySQL password

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Set content type to display HTML


response.setContentType("text/html");
PrintWriter out = response.getWriter();

// 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");

// Establish a connection to the database


Connection connection = DriverManager.getConnection(jdbcURL, jdbcUsername,
jdbcPassword);

// Create a SQL statement object


Statement statement = connection.createStatement();

// Execute SQL query to fetch user data


String sql = "SELECT id, name, email FROM users";
ResultSet resultSet = statement.executeQuery(sql);

// Process the ResultSet and display users


out.println("<table border='1'>");
out.println("<tr><th>ID</th><th>Name</th><th>Email</th></tr>");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String email = resultSet.getString("email");
out.println("<tr><td>" + id + "</td><td>" + name + "</td><td>" + email + "</td></tr>");
}
out.println("</table>");

// Close the connection and statement


resultSet.close();
statement.close();
connection.close();

} catch (Exception e) {
e.printStackTrace(out);
}

out.println("</body></html>");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
doGet(request, response);
}
}

JDBC Connection and Query Execution:

 JDBC URL, Username, Password: These are the connection parameters for connecting to the
MySQL database. Replace them with your own MySQL database credentials.

private String jdbcURL = "jdbc:mysql://localhost:3306/userdb";


private String jdbcUsername = "root";
private String jdbcPassword = "your_password"; // Replace with your own MySQL password

 Loading JDBC Driver: The Class.forName("com.mysql.cj.jdbc.Driver") is used to load


the MySQL JDBC driver.
 Establishing Connection: A Connection object is created using
DriverManager.getConnection() to establish a connection to the MySQL database.
 Creating Statement: A Statement object is created to execute SQL queries.
 Executing Query: The ResultSet is obtained by executing the SQL query (SELECT id, name,
email FROM users).
 Processing ResultSet: The ResultSet is iterated through to get user details and display them in
an HTML table.

HTML Output:

 The servlet generates a simple HTML page containing a table with the user data fetched from the
database.
5. Output:

When you access the servlet via a URL like http://localhost:8080/YourApp/UserServlet,


the browser will display a list of users stored in the database.

<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>

6. MySQL JDBC Driver:

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.

You might also like