0% found this document useful (0 votes)
31 views27 pages

UNIT 5-Server Side Processing

The document outlines the Java Servlet architecture, lifecycle, and its application in handling HTTP GET and POST requests for dynamic web applications. It details the servlet's features, advantages over CGI, and provides examples of servlets for processing form submissions. Additionally, it includes information on web deployment configuration using web.xml for mapping servlets to URLs.

Uploaded by

Sakkaravarthi S
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)
31 views27 pages

UNIT 5-Server Side Processing

The document outlines the Java Servlet architecture, lifecycle, and its application in handling HTTP GET and POST requests for dynamic web applications. It details the servlet's features, advantages over CGI, and provides examples of servlets for processing form submissions. Additionally, it includes information on web deployment configuration using web.xml for mapping servlets to URLs.

Uploaded by

Sakkaravarthi S
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/ 27

RAMCO INSTITUTE OF TECHNOLOGY

Department of Information Technology


Academic Year: 2024 – 2025 (Even Semester)
IT3401 & Web Essentials

UNIT V – SERVLETS AND DATABASE CONNECTIVITY 9

Servlets: Java Servlet Architecture – Servlet Life cycle- Form GET and POST actions -Sessions –
Cookies – Database connectivity - JDBC -Creation of simple interactive applications - Simple
database applications

1.Servlets: Java Servlet Architecture


1.1 Overview of Servlet

➢ Servlet is a Java-based server-side technology that allows developers to create dynamic


web applications.

➢ It is part of the Java Enterprise Edition (Java EE) framework and runs on a web server or
an application server to handle client requests and generate responses dynamically.

1.2 Definition of Java Servlet

A Java Servlet is a server-side program written in Java that extends the functionality of
a web server or application server. It operates as a middle layer between client requests
(typically HTTP requests sent from a web browser or other client) and the server's response.

A Servlet is a Java class that:

1. Processes client requests (HTTP GET, POST, etc.).

2. Generates and sends responses dynamically.

3. Operates within a Servlet Container (e.g., Apache Tomcat, Jetty), which handles
lifecycle management and HTTP request/response processing.

1.3 Features of Java Servlet

1. Platform Independence

• Servlets are written in Java, making them platform-independent.


• They can run on any web server or application server that supports the Java Servlet API,
such as Apache Tomcat or Jetty.
2. Efficiency

Servlets use multithreading to handle multiple client requests simultaneously.


• A single instance of a servlet can serve many requests, unlike CGI (which creates a

new process for each request).


This significantly reduces overhead and improves performance.

3. Dynamic Content Generation

Servlets allow developers to create dynamic content based on user input or backend data.
They can generate responses in various formats, such as:
• HTML for web pages.
• JSON or XML for APIs.
4. Robustness

Java provides features like exception handling, type safety, and garbage collection, making
servlets more robust and reliable compared to traditional server-side scripts.

5. Portability
• The same servlet code can run on any server that adheres to the Servlet API
standard without modifications.
6. Life Cycle Management

• The Servlet API provides methods (init, service, destroy) to manage the lifecycle of
a servlet efficiently.
• The Servlet Container takes care of loading, initializing, and destroying servlets.
7. Session Management
• Servlets provide built-in support for managing sessions using
i) Cookies
ii)URL rewriting
iii) HTTP Session
8. Secured

Java Servlets leverage Java's in-built security features, such as:

• Sandboxed execution environment.

• Secure communication using HTTPS.


1.4 Java Servlet Architecture

The Servlet architecture is based on the Request-Response model and consists of three key
components:
1. Servlet Interface
o The Servlet interface defines the methods that all servlets must implement. It is part of
the javax.servlet package.
o Commonly used methods:
▪ init(ServletConfig config): Initializes the servlet.
▪ service(ServletRequest req, ServletResponse res): Handles client requests and
generates responses.
▪ destroy(): Cleans up resources before the servlet is destroyed.
2. GenericServlet
o It is an abstract class that implements the Servlet interface.
o Provides a simplified framework for servlet development.
o Not tied to any specific protocol.
3. HttpServlet
o A subclass of GenericServlet designed specifically for HTTP protocol.
o Contains methods like:
▪ doGet(HttpServletRequest req, HttpServletResponse res): Handles HTTP GET
requests.
▪ doPost(HttpServletRequest req, HttpServletResponse res): Handles HTTP POST
requests.
▪ doPut, doDelete, etc., for other HTTP methods.
Servlet Workflow
1. Client Request
o The client sends an HTTP request to the web server.
2. Servlet Container
o The server passes the request to the Servlet Container (a part of the web/application
server).
o The container handles servlet lifecycle management, multithreading, and memory
management.
3. Servlet Initialization
o If the servlet is not already loaded, the container:
▪ Loads the servlet class.
▪ Instantiates the servlet.
▪ Calls the init() method.
4. Request Processing
o The container invokes the service() method of the servlet.
o The service() method dispatches requests to appropriate methods (doGet, doPost, etc.).
5. Response Generation
o The servlet processes the request and generates a dynamic response, typically an
HTML, JSON, or XML document.
6. Response Sent to Client
o The response is sent back to the client by the container.

1.5 Advantages of Java Servlet

➢ Platform Independence: Built on Java, servlets are portable across platforms.

➢ Efficiency: Persistent server-side processes reduce overhead compared to CGI.

➢ Robustness: Java’s exception handling and type safety ensure reliability.

➢ Scalability: Multithreaded request handling ensures high scalability.

➢ Integration: Can work seamlessly with databases, frameworks, and APIs.


1.6 Drawbacks of CGI over Servlets

While Common Gateway Interface (CGI) was widely used in the early days of web
development, it has several drawbacks compared to Java Servlets. These limitations make CGI
less efficient and scalable for modern web applications. Here are the key drawbacks of CGI over
Servlets:

Performance and Resource Consumption

• CGI:
o CGI scripts create a new process for every request, which is resource-intensive and
slow.
o Each time a request comes in, a new instance of the CGI program is created, executed,
and terminated, leading to high overhead in terms of memory and CPU usage.
• Servlet:
o Servlets use a single instance (with multiple threads) to handle multiple requests,
which improves performance and reduces resource consumption.
o Servlets are more efficient, especially under heavy traffic.

2.Servlet Life Cycle


➢ The lifecycle of a Java Servlet refers to the process by which a servlet is loaded, initialized,
invoked, and eventually destroyed within a Servlet Container (like Apache Tomcat or Jetty).
➢ This lifecycle is managed by the Servlet Container, which is responsible for creating
instances of the servlet and controlling their execution.
1. Loading and Instantiation

➢ A client (e.g., a web browser) sends a request to the web server, which may or may not
result in the loading of the servlet.

➢ If the servlet hasn’t been loaded yet, the Servlet Container will load it into memory
and instantiate it.

➢ Method: init()
This method is called once, when the servlet is loaded into memory for the first time (or
when the server starts up). The init() method is called only once per servlet lifecycle.

Purpose: It is used to perform any one-time initialization tasks, such as setting up database
connections, reading configuration files, or other necessary setups.

public void init() throws ServletException {

// Initialization code here

The init() method can throw a ServletException if an error occurs during initialization.

2. Request Handling (Service Method)

➢ When a client sends a request (usually an HTTP request), the servlet processes it and
returns a response.

➢ The Servlet Container invokes the service() method of the servlet to handle the request.

➢ Method: service()
This method is called for every client request and is responsible for processing the request
and generating the appropriate response.

Purpose: The service() method takes two parameters: HttpServletRequest (request data) and
HttpServletResponse (response data). It can determine the HTTP method (GET, POST, etc.)
and direct the request to the appropriate handler (e.g., doGet(), doPost()).

public void service(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Handle the request here

doGet(request, response); // or doPost(request, response), etc.


}

o The service() method is invoked for every request and should be efficient, as it directly
impacts the response time.

o Typically, the servlet is multithreaded, so multiple requests can be processed


concurrently by invoking the appropriate doGet() or doPost() methods.

3. Request Handling by Specific Methods


➢ Depending on the HTTP request method (e.g., GET, POST), the doXXX() methods
are invoked:
➢ Method: doGet()
Handles HTTP GET requests. It is used for retrieving resources from the server,
such as displaying a web page.

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Handle GET request }

➢ Method: doPost()
Handles HTTP POST requests. It is used for submitting data to the server, such
as form submissions.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Handle POST request}

➢ Similarly, doPut(), doDelete(), etc., handle other HTTP methods.

4. Response Generation

➢ After processing the request, the servlet generates an HTTP response (such as HTML
content, JSON data, or a redirect).

➢ The response is sent back to the client (e.g., browser) by writing to the HttpServletResponse
object.

response.getWriter().write("Hello, World!"); // Example of sending a response

➢ The servlet can also set headers, cookies, or forward the response to another resource (e.g.,
a JSP page).
5. Request Completion and Cleanup (Destroy Method)

➢ When the servlet is no longer needed (e.g., the web application is stopped or the servlet
container is shut down), the servlet container calls the destroy() method before
removing it from memory.

➢ destroy()
The destroy() method is called once during the lifecycle of the servlet, typically when
the servlet container is shutting down or when the servlet is being unloaded.

➢ Purpose: The destroy() method is used for cleanup operations, such as closing database
connections, releasing resources, or performing other shutdown tasks.

public void destroy() {

// Cleanup code here

o After the destroy() method is called, the servlet instance is eligible for garbage
collection.

Servlet Lifecycle Flow

1. Client Request: The client sends an HTTP request to the server.

2. Servlet Loading: If the servlet isn’t already loaded, the container loads the servlet.

3. Initialization: The container calls init() to initialize the servlet.

4. Request Handling: The service() method is invoked to handle the request, which internally
calls the relevant doGet() or doPost() methods.

5. Response Generation: The servlet generates an appropriate response and sends it back to
the client.

6. Destruction: When the servlet is no longer needed, the container calls destroy() to clean up
resources.
3.FORM GET AND POST ACTIONS
In a Java web application, servlets are used to handle form submissions using HTTP GET and
POST methods. The form data sent by the client (via a web browser) is processed by the servlet,
which then generates a response.

1. Example: HTML Form (Client Side)


First, create a simple HTML form that sends data using the GET or POST method to a servlet.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Submission</title>
</head>
<body>
<!-- Form for GET method -->
<h2>GET Form</h2>
<form action="getFormServlet" method="GET">
Name: <input type="text" name="name" required><br><br>
Age: <input type="text" name="age" required><br><br>
<input type="submit" value="Submit GET">
</form>
<!-- Form for POST method -->
<h2>POST Form</h2>
<form action="postFormServlet" method="POST">
Name: <input type="text" name="name" required><br><br>
Age: <input type="text" name="age" required><br><br>
<input type="submit" value="Submit POST">
</form>
</body>
</html>

• The first form sends data via the GET method to the servlet getFormServlet.
• The second form sends data via the POST method to the servlet postFormServlet.
• Both forms contain input fields for the user’s name and age.
2. Servlet for Handling GET Request (getFormServlet)

When the form uses the GET method, the servlet retrieves the data from the query string (URL
parameters).
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetFormServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Retrieve form data from query string
String name = request.getParameter("name");
String age = request.getParameter("age");

// Set content type and prepare to write the response


response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Output the received data
out.println("<html><body>");
out.println("<h2>Received GET Data:</h2>");
out.println("<p>Name: " + name + "</p>");
out.println("<p>Age: " + age + "</p>");
out.println("</body></html>");
}
}
• The doGet() method handles the GET request.
• request.getParameter("name") and request.getParameter("age") are used to retrieve the form
data sent via the query string in the URL.
• The data is then written to the response in HTML format.
3. Servlet for Handling POST Request (postFormServlet)

For the POST method, the servlet retrieves the form data from the request body.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PostFormServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Retrieve form data from the request body
String name = request.getParameter("name");
String age = request.getParameter("age");
// Set content type and prepare to write the response
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Output the received data
out.println("<html><body>");
out.println("<h2>Received POST Data:</h2>");
out.println("<p>Name: " + name + "</p>");
out.println("<p>Age: " + age + "</p>");
out.println("</body></html>");
}
}
• The doPost() method handles the POST request.
• Similar to the GET method, request.getParameter("name") and request.getParameter("age")
are used to retrieve the form data, but this time the data is sent in the request body (not the
URL).
• The servlet generates a response displaying the received data.

4. Web Deployment Configuration (web.xml)

In a real application, ou need to map these servlets to URLs in the web.xml deployment descriptor.

<web-app xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

version="3.0">

<!-- Mapping for GET form servlet -->

<servlet>

<servlet-name>GetFormServlet</servlet-name>
<servlet-class>GetFormServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>GetFormServlet</servlet-name>

<url-pattern>/getFormServlet</url-pattern>

</servlet-mapping>

<!-- Mapping for POST form servlet -->

<servlet>

<servlet-name>PostFormServlet</servlet-name>

<servlet-class>PostFormServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>PostFormServlet</servlet-name>

<url-pattern>/postFormServlet</url-pattern>

</servlet-mapping>

</web-app>

• The <servlet> and <servlet-mapping> tags in web.xml configure the URL patterns
(/getFormServlet and /postFormServlet) to point to the respective servlet classes.

5. Running the Example

1. Compile the Java Servlets and deploy the .class files to the WEB-INF/classes directory of
your web application.
2. Configure the web.xml file as shown above.
3. Start your servlet container (e.g., Apache Tomcat).
4. Open a web browser and navigate to the HTML form (e.g., http://localhost:8080/your-
app/index.html).
5. Fill out the form and submit it:
o The GET form will display the submitted data in the URL.
o The POST form will display the submitted data without exposing it in the URL.
4. SESSION TRACKING-COOKIES IN JAVA SERVLET
Session Tracking:

• Session simply means a particular interval of time.


• Session Tracking is a way to maintain state (data) of an user.
• Http protocol is a stateless, each request is considered as the new request, so we need to
maintain state using session tracking techniques.
• Each time user requests to the server, server treats the request as the new request. So we need to
maintain the state of an user to recognize to particular user.

• We use session tracking to recognize the user It is used to recognize the particular user.
• Session Tracking Techniques
– Cookies
– Hidden Form Field
– URL Rewriting
– HttpSession

Cookies

Cookies are text files stored on the client computer and they are kept for various information tracking
purpose
There are three steps involved in identifying returning users:
o Server script sends a set of cookies to the browser in response header.
o Browser stores this information on local machine for future use.
o When next time browser sends any request to web server then it sends those cookies
information to the server in request header and server uses that information to identify the
user.
Cookies are created using Cookie class present in Servlet API.
For adding cookie or getting the value from the cookie, we need some methods provided by other
interfaces. They are:
a. public void addCookie(Cookie ck): method of HttpServletResponse interface is used
to add cookie in response object.
b. public Cookie[] getCookies(): method of HttpServletRequest interface is used to return
all the cookies from the browser.
Disadvantage of Cookies

• It will not work if cookie is disabled from thebrowser.


• Only textual information can be set in Cookie object.

Methods

public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.

public String getName() Returns the name of the cookie. The name cannot
be changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String name) changes the name of the cookie.
public void setValue(String value) changes the value of the cookie.

Create Cookie

Cookie ck=new Cookie("user","kalpana ");//creating cookie object


response.addCookie(ck);//adding cookie in the response

Delete Cookie

It is mainly used to logout or signout the user.


Cookie ck=new Cookie("user",""); //deleting value of cookie
ck.setMaxAge(0); //changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response

Get Cookies

Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++)
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue()); //printing name and value of cookie
Sending the Cookie into the HTTP response headers:

We use response.addCookie to add cookies in the HTTP response header as follows:


response.addCookie(cookie);

Ex: List and AddCookie.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ListandAddCookieextends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie cookie = null;
out.println("<html><body>"+
"<form method='get' action='/mrcet/CookieLab'>"+
"Name:<input type='text' name='user' /><br/>"+
"Password:<input type='text' name='pass' ><br/>"+
"<input type='submit' value='submit'>"+
"</form>");
String name = request.getParameter("user");
String pass = request.getParameter("pass");
if(!pass.equals("") || !name.equals(""))
{
Cookie ck = new Cookie(name,pass);
response.addCookie(ck);
}
Cookie[] cookies = request.getCookies();
if( cookies != null ){
out.println("<h2> Found Cookies Name and Value</h2>");
for (inti = 0; i<cookies.length; i++){
cookie = cookies[i];
out.print("Cookie Name : " + cookie.getName() + ", ");
out.print("Cookie Value: " + cookie.getValue()+" <br/>");
}
}
out.println("</body></html>");
}
}
web.xml

<web-app>
<servlet>
<servlet-name>ListandAddCookie</servlet-name>
<servlet-class>ListandAddCookie</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ListandAddCookie</servlet-name>
<url-pattern>/ListandAddCookie</url-pattern>
</servlet- mapping>
</web-app>

Output:

HttpSession

• HttpSession Interface provides a way to identify a user across more than one page request or visit
to a Web site and to store information about that user.
• Web container creates a session id for each user. The container uses this id to identify the
particular user.
• The servlet container uses this interface to create a session between an HTTP client and an HTTP
server.
• The session persists for a specified time period, across more than one connection or page request
from the user.
Get the HttpSession object

The HttpServletRequest interface provides two methods to get the object of HttpSession:
1. publicHttpSessiongetSession():Returns the current session associated with this
request, or if the request does not have a session, creates one.
2. publicHttpSessiongetSession(boolean create):Returns the current HttpSession
associated with this request or, if there is no current session and create is true, returns
a new session.

Destroy Session

session.invalidate();

Set/Get data in session

session.setAttribute(name,value);
session.getAttribute(name);

Methods

1. public String getId(): Returns a string containing the unique identifier value.
2. public long getCreationTime():Returns the time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the client sent a request
associated with this session, as the number of milliseconds since midnight January 1,
1970 GMT.
4. public void invalidate(): Invalidates this session then unbinds any objects bound to it.

Steps

• On client's first request, the Web Container generates a unique session ID and gives it back to the
client with response. This is a temporary session created by web container.
• The client sends back the session ID with each request. Making it easier for the web
container to identify where the request is coming from.
The Web Container uses this ID
Ex: SessionTrack.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionTrack extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
// Create a session object if it is already not created.
HttpSession session = request.getSession(true);

String title = "Welcome to my website";


String userID = "";
Integer visitCount = new Integer(0);
if (session.isNew())
{
userID = "Kalpana"; session.setAttribute("UserId", "Kalpana");
}
else {
visitCount = (Integer)session.getAttribute("visitCount");
visitCount = visitCount + 1;
userID = (String)session.getAttribute("UserId");
}
session.setAttribute("visitCount", visitCount);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>"+"<body>" +
"<h1>Session Infomation</h1>" +
"<table border='1'>" +
"<tr><th>Session info</th><th>value</th></tr>" +
"<tr><td>id</td><td>" + session.getId() + "</td></tr>" +
"<tr><td>User ID</td<td>" + userID + ―</td></tr>" +
"<tr><td>Number of visits</td><td>" + visitCount +
"</td></tr>" + "</table></body></html>");
}
}

web.xml

<web-app>
<servlet>
<servlet-name>SessionTrack</servlet-name>
<servlet-class>SessionTrack</servlet-class>

</servlet>
<servlet-mapping>
<servlet-name>SessionTrack</servlet-name>
<url-pattern>/SessionTrack</url-pattern>
</servlet- mapping>
</web-app>

5. Database connectivity - JDBC


➢ Servlets can communicate with databases via JDBC (Java Database Connectivity). JDBC
provides a uniform way for a Java program to connect with a variety of databases in a general
manner without having to deal with the specifics of those database systems.
➢ JDBC is an API (Application Programming Interface) in Java that allows applications to
interact with relational databases. It provides a standard set of interfaces and classes to connect to
a database, execute SQL queries, and process the results.
Features of JDBC
1. Platform-Independent: JDBC is written in Java, making it platform-independent and
portable.
2. Database-Independent: It supports multiple database systems like MySQL, PostgreSQL,
Oracle, SQL Server, etc., using specific JDBC drivers.
3. Dynamic SQL Execution: It allows dynamic execution of SQL queries, including
parameterized queries.
4. Exception Handling: Uses SQLException for handling database-related errors.
5. Supports Transactions: JDBC supports transaction management for database operations.

Components of JDBC
1. JDBC Drivers:
o JDBC drivers are required to connect to a specific database.
o Types of JDBC Drivers:
▪ Type 1: JDBC-ODBC Bridge Driver (obsolete and rarely used).
▪ Type 2: Native-API Driver.
▪ Type 3: Network Protocol Driver.
▪ Type 4: Thin Driver (most commonly used as it is written in pure Java).
2. JDBC API:
o Provides classes and interfaces for connecting to and interacting with databases.
o Key classes and interfaces:
▪ DriverManager: Manages database connections.
▪ Connection: Represents a connection to the database.
▪ Statement/PreparedStatement/CallableStatement: Used for executing SQL
commands.
▪ ResultSet: Used for handling the results of a query.
▪ SQLException: Handles database-related exceptions.
Steps in JDBC Programming
Here are the key steps for using JDBC to connect to a database and perform operations:
Step 1: Import the JDBC Package
import java.sql.*;
Step 2: Load and Register the JDBC Driver
• The driver is the middleware between the application and the database.
• Use Class.forName() to load the driver
Class.forName("com.mysql.cj.jdbc.Driver"); // MySQL Driver
Step 3: Establish a Database Connection
• Use the DriverManager.getConnection() method to connect to the database.
Connection connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/testdb",
"username", "password");
Parameters:
• URL: The JDBC URL specifies the protocol, subprotocol, and database name.
• Username: Database username.
• Password: Database password.
Step 4: Create a Statement
• A Statement, PreparedStatement, or CallableStatement object is created to execute SQL
queries.
Statement statement = connection.createStatement();
• For parameterized queries, use PreparedStatement
PreparedStatement preparedStatement = connection.prepareStatement("SELECT *
FROM users WHERE id = ?");
preparedStatement.setInt(1, 1);
Step 5: Execute SQL Queries
• Use the Statement or PreparedStatement to execute SQL commands.
• For SELECT statements
ResultSet resultSet = statement.executeQuery("SELECT * FROM users");
• For INSERT, UPDATE, or DELETE statements
int rowsAffected = statement.executeUpdate("INSERT INTO users (name, email)
VALUES ('John', '[email protected]')");
Step 6: Process the results
• Use a ResultSet to retrieve the results of a SELECT query
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}

Step 7: Close Resources


• Always close the ResultSet, Statement, and Connection to free resources.
• Use a finally block or try-with-resources to ensure proper closure:

Advantages of JDBC
1. Easy integration with Java applications.
2. Platform-independent and supports multiple databases.
3. Supports transaction management.
4. Facilitates dynamic execution of SQL commands.
6. Creation of Simple Interactive Applications
➢ creating a simple interactive Java Servlet application with database connectivity to manage
student details. Example Program to add student records and display it.
➢ Application Requirements
1. A MySQL database named studentdb with a table students.
2. A Java Servlet for interaction.
3. A Web Server such as Apache Tomcat
➢ Database Setup
Create the studentdb database:
CREATE DATABASE studentdb;
Create the students table
CREATE TABLE students ( id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL,
age INT NOT NULL );
➢ Program
AddStudentServlet.java
This servlet allows users to add student details to the database.
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddStudentServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Retrieve form data


String name = request.getParameter("name");
String email = request.getParameter("email");
int age = Integer.parseInt(request.getParameter("age"));

// Database connection details


String jdbcURL = "jdbc:mysql://localhost:3306/studentdb";
String dbUser = "root";
String dbPassword = "password";

Connection connection = null;


PreparedStatement preparedStatement = null;

try {
// Load JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish connection
connection = DriverManager.getConnection(jdbcURL, dbUser, dbPassword);

// Insert query
String sql = "INSERT INTO students (name, email, age) VALUES (?, ?, ?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, name);
preparedStatement.setString(2, email);
preparedStatement.setInt(3, age);

int rows = preparedStatement.executeUpdate();


if (rows > 0) {
out.println("<h2>Student added successfully!</h2>");
}
} catch (Exception e) {
e.printStackTrace(out);
} finally {
try {
if (preparedStatement != null) preparedStatement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace(out);
}
}
}
}

ViewStudentsServlet.java
This servlet displays all students in the database.
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ViewStudentsServlet extends HttpServlet {


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Database connection details


String jdbcURL = "jdbc:mysql://localhost:3306/studentdb";
String dbUser = "root";
String dbPassword = "password";
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;

try {
// Load JDBC Driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish connection
connection = DriverManager.getConnection(jdbcURL, dbUser, dbPassword);

// Execute query
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT * FROM students");

// Display student records


out.println("<h2>Student Details</h2>");
out.println("<table border='1'>");
out.println("<tr><th>ID</th><th>Name</th><th>Email</th><th>Age</th></tr>");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String email = resultSet.getString("email");
int age = resultSet.getInt("age");

out.println("<tr><td>" + id + "</td><td>" + name + "</td><td>" + email + "</td><td>"


+ age + "</td></tr>");
}
out.println("</table>");
} catch (Exception e) {
e.printStackTrace(out);
} finally {
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace(out);
}
}
}
}

index.html

This is the home page that links to the other pages.

<!DOCTYPE html>
<html>
<head>
<title>Student Management</title>
</head>
<body>
<h1>Welcome to Student Management System</h1>
<a href="add-student.html">Add Student</a> |
<a href="view-students">View Students</a>
</body>
</html>

add-student.html

This page allows users to enter student details.


<!DOCTYPE html>
<html>
<head>
<title>Add Student</title>
</head>
<body>
<h2>Add Student Details</h2>
<form action="add-student" method="post">
Name: <input type="text" name="name" required><br><br>
Email: <input type="email" name="email" required><br><br>
Age: <input type="number" name="age" required><br><br>
<input type="submit" value="Add Student">
</form>
</body>
</html>

7. Simple Database Applications


creating a simple database application using Java Servlets.

Load the JDBC Driver.


Establish a database connection.
Create a Statement or PreparedStatement.
Execute SQL queries.
Process the results (if applicable).
Close all database resources.
Integrate the JDBC code within a servlet to handle client requests and respond with results.
Program:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class JdbcServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String jdbcURL = "jdbc:mysql://localhost:3306/testdb";


String dbUser = "root";
String dbPassword = "password";
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
// Step 1: Load the driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Step 2: Establish connection
connection = DriverManager.getConnection(jdbcURL, dbUser, dbPassword);

// Step 3: Create a statement


statement = connection.createStatement();
// Step 4: Execute a query
String sql = "SELECT * FROM users";
resultSet = statement.executeQuery(sql);
// Step 5: Process the result
out.println("<html><body><h1>User Details</h1>");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String email = resultSet.getString("email");
out.println("<p>ID: " + id + ", Name: " + name + ", Email: " + email + "</p>");
}
out.println("</body></html>");
} catch (Exception e) {
e.printStackTrace(out);
} finally {

// Step 6: Close resources


try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace(out);
}
}
}
}

Advantages of Database applications using Servlet:


1. Platform Independence
• Java Servlets are platform-independent and can run on any server or operating system that
supports Java (like Windows, Linux, or macOS).
• This ensures that the database application can be deployed across different platforms
seamlessly.
2. Scalability
• Servlets are designed to handle a large number of requests simultaneously.
• They are multi-threaded, so one instance can serve multiple requests, reducing resource
consumption compared to traditional CGI scripts.
• When integrated with a database, servlets can handle multiple concurrent queries efficiently.
3. Session Management
• Servlets provide robust session management, allowing the application to maintain user-
specific data (like login sessions) across multiple requests.
• This is particularly useful for database-driven applications where user-specific data needs to be
retrieved or updated frequently.
4. Reusability
• A single servlet instance can handle multiple requests, which promotes code reusability.
• The database logic can also be reused across different parts of the application by encapsulating
it in utility or helper classes.

You might also like