UNIT 5-Server Side Processing
UNIT 5-Server Side Processing
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
➢ 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.
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.
3. Operates within a Servlet Container (e.g., Apache Tomcat, Jetty), which handles
lifecycle management and HTTP request/response processing.
1. Platform Independence
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
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.
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:
• 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.
➢ 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.
The init() method can throw a ServletException if an error occurs during initialization.
➢ 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()).
o The service() method is invoked for every request and should be efficient, as it directly
impacts the response time.
➢ Method: doPost()
Handles HTTP POST requests. It is used for submitting data to the server, such
as form submissions.
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.
➢ 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.
o After the destroy() method is called, the servlet instance is eligible for garbage
collection.
2. Servlet Loading: If the servlet isn’t already loaded, the container loads 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.
• 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");
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.
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">
<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>
<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.
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:
• 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
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
Delete Cookie
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:
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();
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);
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>
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);
}
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();
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);
ViewStudentsServlet.java
This servlet displays all students in the database.
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
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");
index.html
<!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
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();