0% found this document useful (0 votes)
5 views50 pages

Updated Module 4

Module 4 introduces servlet technology for creating web applications, detailing the servlet life cycle, advantages over CGI, and the Servlet API. It covers the creation and running of servlets using Eclipse, including examples with HTML and JSP. Additionally, it provides a step-by-step guide for implementing a factorial calculator servlet.

Uploaded by

4al22cs128
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)
5 views50 pages

Updated Module 4

Module 4 introduces servlet technology for creating web applications, detailing the servlet life cycle, advantages over CGI, and the Servlet API. It covers the creation and running of servlets using Eclipse, including examples with HTML and JSP. Additionally, it provides a step-by-step guide for implementing a factorial calculator servlet.

Uploaded by

4al22cs128
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/ 50

Module 4

Introducing servlets: Background; The Life Cycle of a Servlet; Using Tomcat for Servlet Development;
A simple Servlet; The Servlet API; The Jakarta. Servlet Package; Reading Servlet Parameter; The
Jakarta.servlet.http package; Handling HTTP Requests and Responses; Using Cookies; Session
Tracking.
Java Server Pages (JSP); JSP tags, Variables and Objects, Methods, Control statements, Loops, Request
String, Parsing other information, User sessions, Cookies, Session Objects

Introducing servlets

Servlet technology is used to create web application (resides at server side and generates dynamic web
page).

Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common
Gateway Interface) scripting language was popular as a server-side programming language. But there
was many disadvantages of this technology. We have discussed these disadvantages below.

There are many interfaces and classes in the servlet API such as Servlet, GenericServlet, HttpServlet,
ServletRequest, ServletResponse etc.

What is a Servlet?
Servlet can be described in many ways, depending on the context.

 Servlet is a technology i.e. used to create web application.


 Servlet is an API that provides many interfaces and classes including documentations.
 Servlet is an interface that must be implemented for creating any servlet.
 Servlet is a class that extend the capabilities of the servers and respond to the incoming request.
It can respond to any type of requests.
 Servlet is a web component that is deployed on the server to create dynamic web page.

What is web application?

A web application is an application accessible from the web. A web application is composed of web
components like Servlet, JSP, Filter etc. and other components such as HTML. The web components
typically execute in Web Server and respond to HTTP request.

CGI(Commmon Gateway Interface)

CGI technology enables the web server to call an external program and pass HTTP request information
to the external program to process the request. For each request, it starts a new process.
Disadvantages of CGI

There are many problems in CGI technology:

1. If number of clients increases, it takes more time for sending response.


2. For each request, it starts a process and Web server is limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.
Advantage of Servlet

There are many advantages of servlet over CGI. The web container creates threads for handling the
multiple requests to the servlet. Threads have a lot of benefits over the Processes such as they share a
common memory area, lightweight, cost of communication between the threads are low. The basic
benefits of servlet are as follows:

1. better performance: because it creates a thread for each request not process.
2. Portability: because it uses java language.
3. Robust: Servlets are managed by JVM so we don't need to worry about memory leak, garbage
collection etc.
4. Secure: because it uses java language..

The Life Cycle of a Servlet

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:

1. Servlet class is loaded.

2. Servlet instance is created.

3. init method is invoked.

4. service method is invoked.

5. destroy method is invoked.


As displayed in the above diagram, there are three states of a servlet: new, ready and end. The servlet is
in new state if servlet instance is created. After invoking the init() method, Servlet comes in the ready
state. In the ready state, servlet performs all the tasks. When the web container invokes the destroy()
method, it shifts to the end state.

1) Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is loaded when the first request
for the servlet is received by the web container.

2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class. The servlet instance is
created only once in the servlet life cycle.

3) init method is invoked

The web container calls the init method only once after creating the servlet instance. The init method is
used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of
the init method is given below:

public void init(ServletConfig config) throws ServletException

4) service method is invoked

The web container calls the service method each time when request for the servlet is received. If servlet
is not initialized, it follows the first three steps as described above then calls the service method. If
servlet is initialized, it calls the service method. Notice that servlet is initialized only once. The syntax
of the service method of the Servlet interface is given below:
public void service(ServletRequest request, ServletResponse response) throws ServletException,
IOException

5) destroy method is invoked

The web container calls the destroy method before removing the servlet instance from the service. It
gives the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of
the destroy method of the Servlet interface is given below:

public void destroy()


Creation of servlet using three ways through Eclipse

The step by step procedure for creating a servlet

1. running a servlet without any html


2. running a servlet with html
3. running a servlet with JSP

The step-by-step procedure for creating and running servlets in different scenarios.

Running a Servlet without HTML:

Step 1: Create a Dynamic Web Project

Open Eclipse
File → New → Dynamic Web Project
Enter project name (e.g., "SimpleServlet")
Select Tomcat v9.0 as target runtime
Click Finish

Step 2: Create a Servlet

Right-click on src folder


New → Servlet
Enter package name (e.g., "com.example")
Enter servlet name (e.g., "FirstServlet")
Click Finish

Here's a simple servlet example:

package com.servlet;

import java.io.IOException;
import java.io.PrntWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class HelloWorld
*/
@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public HelloWorld() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h2><font color=blue>Hello World!!! </font></h2>");
out.println("</body></html>");
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub

doGet(request, response);
}

Step 3: Run the Servlet

Right-click on project
Run As → Run on Server
Select Tomcat v9.0
Access via: http://localhost:8080/SimpleServlet/FirstServlet
Running a Servlet with HTML:

Step 1: Create HTML File

Right-click on WebContent folder


New → HTML File
Name it (e.g., "index.html")
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
</head>
<body>
<h2>Simple Addition Calculator</h2>
<form action="add" method="post">
Enter First Number: <input type="number" name="num1" required><br><br>
Enter Second Number: <input type="number" name="num2" required><br><br>
<input type="submit" value="Add Numbers">
</form>
</body>
</html>

Step 2: Create Servlet

package com.AdditionServlet;
import java.io.IOException;
import java.io.PrintWriter;
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("/add")
public class AdditionServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

try {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
int sum = num1 + num2;

out.println("<html>");
out.println("<head><title>Addition Result</title></head>");
out.println("<body>");
out.println("<h2>Addition Result</h2>");
out.println("<p>" + num1 + " + " + num2 + " = " + sum + "</p>");
out.println("<br><a href='index.html'>Back to Calculator</a>");
out.println("</body>");
out.println("</html>");
} catch (Exception e) {
out.println("<html>");
out.println("<head><title>Error</title></head>");
out.println("<body>");
out.println("<h2>Error</h2>");
out.println("<p>Please enter valid numbers</p>");
out.println("<br><a href='index.html'>Back to Calculator</a>");
out.println("</body>");
out.println("</html>");
}
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.sendRedirect("index.html");
}
}

Step 3: Run

Right-click project → Run As → Run on Server


Access via:http://localhost:8080/AdditionServletDemo/add
Running a Servlet with JSP:

Step 1: Create JSP File

Right-click on WebContent
New → JSP File

calculator.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<style>
.calculator-form {
margin: 20px;
padding: 20px;
border: 1px solid #ccc;
width: 300px;
}
.form-group {
margin: 10px 0;
}
</style>
</head>
<body>
<div class="calculator-form">
<h2>Simple Calculator</h2>
<form action="calculate" method="post">
<div class="form-group">
First Number: <input type="number" name="num1" required step="any">
</div>
<div class="form-group">
Second Number: <input type="number" name="num2" required step="any">
</div>
<div class="form-group">
Operation:
<select name="operation" required>
<option value="add">Addition (+)</option>
<option value="subtract">Subtraction (-)</option>
<option value="multiply">Multiplication (*)</option>
<option value="divide">Division (/)</option>
</select>
</div>
<input type="submit" value="Calculate">
</form>

<%-- Display result if available --%>


<% if(request.getAttribute("result") != null) { %>
<div style="margin-top: 20px;">
<strong>Result: <%= request.getAttribute("result") %></strong>
</div>
<% } %>

<%-- Display error if available --%>


<% if(request.getAttribute("error") != null) { %>
<div style="margin-top: 20px; color: red;">
<strong>Error: <%= request.getAttribute("error") %></strong>
</div>
<% } %>
</div>
</body>
</html>

Step 2: Create Servlet (CalculatorServlet.java)

package com.calculator;
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("/calculate")
public class CalculatorServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

try {
// Get parameters
double num1 = Double.parseDouble(request.getParameter("num1"));
double num2 = Double.parseDouble(request.getParameter("num2"));
String operation = request.getParameter("operation");

// Perform calculation
double result = 0;
switch(operation) {
case "add":
result = num1 + num2;
break;
case "subtract":
result = num1 - num2;
break;
case "multiply":
result = num1 * num2;
break;
case "divide":
if(num2 == 0) {
request.setAttribute("error", "Cannot divide by zero!");
request.getRequestDispatcher("calculator.jsp").forward(request, response);
return;
}
result = num1 / num2;
break;
default:
request.setAttribute("error", "Invalid operation!");
request.getRequestDispatcher("calculator.jsp").forward(request, response);
return;
}

// Format result to avoid long decimal numbers


String formattedResult = String.format("%.2f", result);

// Set result attribute and forward back to JSP


request.setAttribute("result", formattedResult);
request.getRequestDispatcher("calculator.jsp").forward(request, response);

} catch(NumberFormatException e) {
request.setAttribute("error", "Please enter valid numbers!");
request.getRequestDispatcher("calculator.jsp").forward(request, response);
}
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Redirect GET requests to the calculator page
response.sendRedirect("calculator.jsp");
}
}

Step 3: Run

Right-click project → Run As → Run on Server


Access via: http://localhost:8080/CalculatorDemoProject/calculate

i/p and o/p


Build a servlet program to find the factorial of a number using HTML with step by step proceducre

Step by step implementation procedure:


 Create a new Dynamic Web Project:
o Open Eclipse
o File → New → Dynamic Web Project
o Name it "FactorialCalculatorDemo"
o Choose Apache Tomcat as the target runtime
o Click Finish

 Create the Servlet:


o Right-click on src folder
o New → Class
o Name it "FactorialServlet"
o Copy the Java code from the second artifact above
o Save the file

package com.factorial;

import java.io.IOException;
import java.io.PrintWriter;
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("/factorial")
public class FactorialServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

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

try {
// Get the number from the form
int number = Integer.parseInt(request.getParameter("number"));
// Validate the input
if (number < 0) {
throw new IllegalArgumentException("Number cannot be negative");
}
if (number > 20) {
throw new IllegalArgumentException("Number too large, maximum allowed is 20");
}

// Calculate factorial
long factorial = 1;
String calculation = "Calculation steps:<br>";

if (number == 0 || number == 1) {
factorial = 1;
calculation += number + "! = 1";
} else {
calculation += number + "! = " + number;
for (int i = number; i >= 1; i--) {
factorial *= i;
if (i != number) {
calculation += " × " + i;
}
}
calculation += " = " + factorial;
}

// Generate the response


out.println("<html>");
out.println("<head>");
out.println("<title>Factorial Result</title>");
out.println("<style>");
out.println(".container { margin: 20px; padding: 20px; width: 500px; border: 1px solid #ccc;
border-radius: 5px; }");
out.println(".result { margin: 10px 0; }");
out.println("</style>");
out.println("</head>");
out.println("<body>");
out.println("<div class='container'>");
out.println("<h2>Factorial Result</h2>");
out.println("<div class='result'>");
out.println("<p>Number: " + number + "</p>");
out.println("<p>Factorial: " + factorial + "</p>");
out.println("<p>" + calculation + "</p>");
out.println("</div>");
out.println("<a href='index.html'>Calculate Another Factorial</a>");
out.println("</div>");
out.println("</body>");
out.println("</html>");

} catch (NumberFormatException e) {
displayError(out, "Please enter a valid number");
} catch (IllegalArgumentException e) {
displayError(out, e.getMessage());
}
}

private void displayError(PrintWriter out, String message) {


out.println("<html>");
out.println("<head><title>Error</title></head>");
out.println("<body>");
out.println("<div style='margin: 20px; color: red;'>");
out.println("<h2>Error</h2>");
out.println("<p>" + message + "</p>");
out.println("<a href='index.html'>Try Again</a>");
out.println("</div>");
out.println("</body>");
out.println("</html>");
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.sendRedirect("index.html");
}
}

3. Create the HTML file:


o Right-click on WebContent folder
o New → HTML File
o Name it "index.html"
<!DOCTYPE html>
<html>
<head>
<title>Factorial Calculator</title>
<style>
.container {
margin: 20px;
padding: 20px;
width: 300px;
border: 1px solid #ccc;
border-radius: 5px;
}
.form-group {
margin: 10px 0;
}
</style>
</head>
<body>
<div class="container">
<h2>Factorial Calculator</h2>
<form action="factorial" method="post">
<div class="form-group">
Enter a number:
<input type="number" name="number" min="0" max="20" required>
<small>(Max: 20)</small>
</div>
<input type="submit" value="Calculate Factorial">
</form>
</div>
</body>
</html>

i/p and o/p


The Servlet API

The Servlet API is a Java technology for building web applications. Here's a practical example of a
basic Servlet:

Key components:
 @WebServlet: Maps servlet to URL pattern
 HttpServletRequest: Contains client request data
 HttpServletResponse: Sends response to client
 doGet/doPost: Handle HTTP GET/POST requests
To deploy, add this servlet to a Java web application in a servlet container like Tomcat. Access via:
http://localhost:8080/yourapp/hello?name=Dr.Sm.Badhusha

HelloServlet.java

package com.example;

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;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Set response content type


response.setContentType("text/html");

// Get writer
PrintWriter out = response.getWriter();

// Get parameter from request


String name = request.getParameter("name");
if (name == null) name = "Dr.Sm.Badhusha";

// Write HTML response


out.println("<html>");
out.println("<head><title>Hello Servlet</title></head>");
out.println("<body>");
out.println("<font color=blue><h1>Hello, " + name + "!</h1></font>");
out.println("<font color=magenta><p>Current time: " + new java.util.Date() + "</p></font>");
out.println("</body></html>");
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Jakarta Servlet Example

Key differences from javax.servlet:

 Package name changed to jakarta.servlet


 Requires Jakarta EE 9+ or Jakarta EE Web Profile
 Compatible with newer Java features like text blocks
 Deployment requires Jakarta EE compliant server (e.g., Tomcat 10+)
Access via: http://localhost:8080/yourapp/studentForm

package com.Jakarta;

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;
import java.io.*;

@WebServlet("/studentForm")
public class StudentServlet extends HttpServlet {

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

out.println("""
<html>
<body>
<h2>Student Registration</h2>

<form action="studentForm" method="post">


<table>
<tr><td>ID:</td><td><input type="text" name="id"></td></tr>
<tr><td> Name:</td><td><input type="text" name="name"></td></tr>
<tr><td> Course: </td><td><input type="text" name="course"></td></tr>

</table>
<br><input type="submit" value="Register">
</form>
</body>
</html>
""");
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Reading servlet parameters
String id = request.getParameter("id");
String name = request.getParameter("name");
String course = request.getParameter("course");

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

out.println("""
<html>
<body>
<h2>Registration Successful</h2>
<p>Student ID: %s</p>
<p>Name: %s</p>
<p>Course: %s</p>
</body>
</html>
""".formatted(id, name, course));
}
}
HTTP Request/Response flow works with Servlets and JSP:

Project Structure:

CopyWebContent/
├── WEB-INF/
│ └── web.xml (if needed)
├── index.jsp
├── result.jsp
└── classes/
└── UserDataServlet.class

HTTP Request Flow:

User accesses index.jsp which displays a form


Form submission creates POST request to /processUser
Servlet processes the request
Results are forwarded to result.jsp

Key Components:
a) Index.jsp (Request Creation):

Creates an HTML form


Uses POST method to send data
Collects username, email, and age
Sends data to servlet at "processUser" URL
b) UserDataServlet (Request Processing):

Receives POST request with form data


Extracts parameters using request.getParameter()
Performs validation
Sets attributes for JSP using request.setAttribute()
Forwards to result page

c) Result.jsp (Response Display):

Receives forwarded request


Accesses attributes using request.getAttribute()
Displays processing results
Shows submitted data if available

Important HTTP Concepts Demonstrated:


a) Request Methods:

POST: Used for form submission


GET: Redirects to form page

b) Request Parameters:

Accessed via request.getParameter()


Names match form field names

c) Request Attributes:

Set with request.setAttribute()


Used to pass data to JSP

d) Response Types:

Forward: Server-side redirect with request data


Redirect: Client-side redirect to new URL

To Deploy and Test:

Deploy to a Java web server (like Tomcat)


Access http://localhost:8080/your-app/index.jsp
Fill and submit the form
Observe the request/response flow
Best Practices Shown:

Separation of concerns (MVC pattern)


Input validation
Error handling
Clean URL mapping
Proper request forwarding
Responsive design with CSS

package com.HTTP_REQ_RES;

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;

//UserDataServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;

@WebServlet("/processUser")
public class UserDataServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Get parameters from the request


String username = request.getParameter("username");
String email = request.getParameter("email");
String designation = request.getParameter("designation");

// Perform some basic validation


String message;
if (username == null || username.trim().isEmpty()) {
message = "Username is required";
} else {
// Process the data (in real app, you might save to database)
message = "User data processed successfully";
// Store data in request attributes to be accessed by JSP
request.setAttribute("username", username);
request.setAttribute("email", email);
request.setAttribute("designation", designation);
}
request.setAttribute("message", message);

// Forward to result JSP


RequestDispatcher dispatcher = request.getRequestDispatcher("/result.jsp");
dispatcher.forward(request, response);
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Redirect GET requests to the input form
response.sendRedirect("index.jsp");
}
}

<!-- index.jsp -->


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>User Data Form</title>
<style>
.form-container {
width: 300px;
margin: 50px auto;
padding: 20px;
border: 1px solid #ccc;
}
.form-field {
margin: 10px 0;
}
</style>
</head>
<body>
<div class="form-container">
<h2>Enter User Data</h2>
<form action="processUser" method="POST">
<div class="form-field">
<label for="username">Username :</label>
<input type="text" id="username" name="username" required>
</div>
<div class="form-field">
<label for="email">Email :</label>
<input type="email" id="email" name="email" required>
</div>
<div class="form-field">
<label for="designation">Designation :</label>
<input type="text" id="designation" name="designation" required>
</div>
<div class="form-field">
<input type="submit" value="Submit">
</div>
</form>
</div>
</body>
</html>

<!-- result.jsp -->


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Result Page</title>
<style>
.result-container {
width: 300px;
margin: 50px auto;
padding: 20px;
border: 1px solid #ccc;
}
.message {
color: green;
margin-bottom: 20px;
}
.error {
color: red;
}
</style>
</head>
<body>
<div class="result-container">
<h2>Processing Result</h2>
<div class="${message.contains('error') ? 'error' : 'message'}">
<%= request.getAttribute("message") %>
</div>

<% if(request.getAttribute("username") != null) { %>


<h3>Submitted Data:</h3>
<p>Username: <%= request.getAttribute("username") %></p>
<p>Email: <%= request.getAttribute("email") %></p>
<p>Designation: <%= request.getAttribute("designation") %></p>
<% } %>

<a href="index.jsp">Back to Form</a>


</div>
</body>
</html>
A servlet program that demonstrates cookie handling with a step-by-step explanation.

Project Setup:

Create a new web project in your IDE


Make sure you have the servlet-api.jar in your project dependencies
Place this servlet class in your project's servlet directory

Configuration:

The @WebServlet("/CookieServlet") annotation maps this servlet to the URL pattern "/CookieServlet"
Alternatively, you can configure it in web.xml if not using annotations

How the Program Works:

When a user first visits, they see a form to enter their name
After submitting, a cookie is created with their name
On subsequent visits, they'll see a welcome message with their name
They can logout, which deletes the cookie

Testing the Program:

Deploy the application to your servlet container (e.g., Tomcat)


Access it through: http://localhost:8080/yourapp/CookieServlet
Enter a name and submit
reload the browser
Page is reloaded and your name is remembered by the cookie till its expiry

Key Features Demonstrated:

Creating cookies
Setting cookie properties (expiration, path)
Reading cookies
Deleting cookies
Basic session management

package com.cookieservlet;
//Step 1: Required imports
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;

//Step 2: Create servlet class and use WebServlet annotation


@WebServlet("/CookieServlet")

public class CookieServlet extends HttpServlet {


int count=0; // count for loading times
// Step 3: Handle GET requests
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

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

// Step 4: Create or retrieve cookies


String userName = request.getParameter("userName");
if (userName != null && !userName.isEmpty()) {
// Create a new cookie
Cookie userCookie = new Cookie("user", userName);

// Step 5: Set cookie properties


userCookie.setMaxAge(60); // Cookie expires in 1 minute
userCookie.setPath("/");

// Step 6: Add cookie to response


response.addCookie(userCookie);
}

// Step 7: Read existing cookies


Cookie[] cookies = request.getCookies();
String existingUser = null;

if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("user")) {
existingUser = cookie.getValue();
break;
}
}
}
// Step 8: Generate HTML response
out.println("<html>");
out.println("<head><title>Cookie Example</title></head>");
out.println("<body>");

if (existingUser != null) {
count+=1;
out.println("<font color=blue><h2>Welcome back, " + existingUser+"!</h2></font>");
out.println("<font color=magenta><h2>You have visited this page "+count+" times!</h2></font>");
}
// Step 9: Add option to delete cookie
// out.println("<form action='CookieServlet' method='post'>");
// out.println("<input type='submit' value='Logout'>");
// out.println("</form>");
else {
out.println("<h2>Welcome Guest!</h2>");
out.println("<form action='CookieServlet' method='get'>");
out.println("Enter your name: <input type='text' name='userName'>");
out.println("<input type='submit' value='Submit'>");
out.println("</form>");
}

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

// Step 10: Handle POST requests (for logout)


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Delete the cookie by setting its max age to 0


Cookie cookie = new Cookie("user", "");
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);

// Redirect back to the servlet


response.sendRedirect("CookieServlet");
}
}
i/p and o/p

Session tracking servlet step by step:

Setup Requirements:

Make sure you have a Java EE compatible web server (like Apache Tomcat)
Java Development Kit (JDK) installed
Servlet API in your project dependencies

Create the Servlet:

Create a new Java class that extends HttpServlet


Add the @WebServlet annotation to specify the URL pattern
The code above creates a servlet mapped to "/SessionTracker"
Session Management Implementation:

Session Tracking

The servlet uses HttpSession to track user sessions It automatically creates a new session if one doesn't exist
using request.getSession(true) Stores and retrieves visit count information in the session
Displays session details like ID, creation time, and last access time

Deployment Steps:

Compile the servlet


Package it in a WAR file with proper web.xml configuration (if not using annotations)
Deploy to your web server's webapps directory

Testing the Servlet:

Start your web server


Access the servlet through your browser: http://localhost:8080/your-app/SessionTracker
Refresh the page to see the visit count increment
Try opening in different browsers to see different sessions

Key Features Demonstrated:

Automatic session creation


Session persistence across requests
Session attribute storage and retrieval
Session timing information tracking

Security Considerations:

The session ID is automatically managed securely by the container


Sessions typically timeout after a period of inactivity (configurable in web.xml)
Consider implementing session timeout handling for production use

SessionTrackingServlet.java

package com.sessiontracking;

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;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.util.Date;

@WebServlet("/SessionTracker")
public class SessionTrackingServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Get the session object


// If session doesn't exist, create a new one
HttpSession session = request.getSession(true);

// Get the session creation time


Date createTime = new Date(session.getCreationTime());

// Get the last access time


Date lastAccessTime = new Date(session.getLastAccessedTime());

// Get the session ID


String sessionId = session.getId();

// Get the visit count from session


Integer visitCount = (Integer) session.getAttribute("visitCount");
if (visitCount == null) {
visitCount = 1;
} else {
visitCount++;
}

// Store the updated visit count in session


session.setAttribute("visitCount", visitCount);

// Set response content type


response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Generate HTML response
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head><title>Session Tracking Demo</title></head>");
out.println("<body>");
out.println("<h2>Session Tracking Information</h2>");
out.println("<p>Session ID: " + sessionId + "</p>");
out.println("<p>Session Creation Time: " + createTime + "</p>");
out.println("<p>Last Access Time: " + lastAccessTime + "</p>");
out.println("<p>Visit Count: " + visitCount + "</p>");
out.println("</body>");
out.println("</html>");
}
}

o/p
Java Server Pages
JavaServer Pages (JSP) is a server-side technology that allows you to create dynamic web content by
combining HTML with Java code. It's part of the Java EE (Enterprise Edition) platform and was designed
to make it easier for developers to build web applications.
Key aspects of JSP:
4. Dynamic Content Generation
5. JSP pages can generate dynamic content based on user input, database data, or other variables

6. Content changes based on programming logic and conditions


HTML with Java
 JSP lets you write regular HTML code and embed Java code within it
 Special tags (<%...%>) are used to include Java code in the page
3. Behind the Scenes
 When a JSP page is requested, it's automatically converted into a servlet
 The server compiles and executes the Java code, then sends the resulting HTML to the client's
browser
4. Common Uses
 Creating dynamic web pages
 Building user interfaces for web applications
 Displaying database results
 Handling form submissions
 Session management
5. Advantages
 Simpler than pure servlets for creating web pages
 Separates presentation from business logic
 Reusable components
 Easy integration with existing Java code

JSP Tags:

Scriptlet Tags <% ... %>

Contains Java code executed during request processing


Example:

<% String name = "John"; %>

Declaration Tags <%! ... %>


Declares methods or fields at class level

<%! int count = 0; %>


<%! public int increment() { return ++count; } %>

Expression Tags <%= ... %>

Outputs values directly to the page

Welcome, <%= name %>!

Directive Tags <%@ ... %>

Page-level instructions

<%@ page language="java" contentType="text/html; charset=UTF-8" %>

Action Tags jsp:...

Predefined functionality

<jsp:include page="header.jsp" />

JSP Implicit Objects:

request - HttpServletRequest object


response - HttpServletResponse object
session - HttpSession object
application - ServletContext object
out - JspWriter for output
pageContext - PageContext object
config - ServletConfig object
page - Reference to the servlet instance
exception - Exception object (in error pages)

Variables:

Local Variables (declared in scriptlets)


jspCopy<%
int x = 10;
String message = "Hello";
%>
Instance Variables (declared in declarations)
<%!
private int counter = 0;
private String title = "My Page";
%>

Control Statements:

If-Else:
<% if (user.isLoggedIn()) { %>
Welcome back!
<% } else { %>
Please log in.
<% } %>

Switch:
<%
switch(userType) {
case "admin": %>
<h1>Admin Panel</h1>
<% break;
case "user": %>
<h1>User Dashboard</h1>
<% break;
} %>

Loops:

For Loop:
<% for(int i = 0; i < 5; i++) { %>
<p>Item <%= i %></p>
<% } %>

While Loop:
<%
int i = 0;
while(i < items.size()) { %>
<li><%= items.get(i) %></li>
<% i++; } %>

Enhanced For Loop:


<% for(String item : itemList) { %>
<div><%= item %></div>
<% } %>
Methods:

Instance Methods:
<%!
public String formatDate(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(date);
}
%>

Using Methods:
<p>Today's date: <%= formatDate(new Date()) %></p>

Session Management using JSP

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="welcome.jsp">
Please Enter your name : <input type="text" name="uname"><br/>
<input type="submit" value="Start the session"><br/>
</form>

</body>
</html>
The name which is entered by user in the index page is displayed on the welcome.jsp page and it saves
the same variable in the session object so that it can be retrieved on any page till the session becomes
inactive.

welcome.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<%
String name=request.getParameter("uname");
out.print("Welcome!"+name);
out.print("<br>Session has started ... "+name);
session.setAttribute("user",name);
out.print("<br>your name has been stored in session object");
session.setMaxInactiveInterval(60);
out.print("<br>One minute is set for the session expiry");
out.print("<br>Kindly press the following link to check it<br>");

%>

<a href="second.jsp">Display the value</a>

</body>
</html>

In second.jsp page, the value of variable is retrieved from the session and displayed.

second.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>designation
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<h1>Display the session value on this page</h1>

<%
String name=(String)session.getAttribute("user");
if(name==null)
out.print("Sorry the session has ended");
else
out.print("Hello "+name);
%>

</body>
</html>
Cookies

Cookies are small pieces of data stored on the client's browser, which can be used to maintain
state information or user preferences across multiple requests.

Browser developers long ago recognized that HTTP’s statelessness poses a huge problem for
Web developers, and thus cookies were born. A cookie is a small piece of information that
browsers store on behalf of Web servers. Every time a browser requests a page from a certain
server, it gives back the cookie that it initially received.

What are cookies and how do they work ?

Cookies are located in browser directories. They are basically a small piece of data sent from a website
and stored in the user’s web browser while the user is browsing and are mainly used for user
identification. That is why when you enter a website using cookies, you may be asked to fill out a
form providing personal information. This information is wrapped into a cookie and sent to your web
browser, which then stores the information for later use. Every time the user goes back to the same
website, the browser retrieves and sends this file to the website’s server.
Here's a brief overview of cookies

 Any web app provides easy-to-use methods for setting and getting cookies.
 Cookies can be set on the HttpResponse object.
 Incoming cookies can be accessed via the request.COOKIES dictionary.
 The session framework uses cookies to store a session ID, with the actual session data stored on
the server side.

Cookie Management using JSP

1. Set a cookie:
 Enter name, domain, and max age (try with 10 seconds)
 Click "Add Cookie"
 See confirmation with details
2. View cookie list:
 Return to main page
 Watch as the cookie automatically disappears after the specified time
 List updates in real-time
3. Added Automatic Expiration:
 Added JavaScript to refresh the page every second
 Added logic to check and remove expired cookies based on their set time and max age
 Stores cookie set time in seconds since epoch for accurate expiration calculation
4. Simplified Display:
 Table now only shows Cookie Name, Domain, and Max Age
 Added note about automatic updates
 Set default max age to 10 seconds for easier testing
5. Enhanced Cookie Management:
 Cookies automatically disappear from the list when they expire
 No manual deletion required
 Maintains accurate list of active cookies

<!-- index.jsp -->


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Cookie List Management</title>
<style>
.cookie-table {
border-collapse: collapse;
width: 60%;
margin: 20px 0;
}
.cookie-table th, .cookie-table td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
.cookie-table th {
background-color: #f2f2f2;
}
.form-group {
margin: 15px 0;
}
.auto-refresh {
color: #666;
font-size: 0.9em;
margin-bottom: 10px;
}
</style>
<script>
// Auto refresh page every 1 second to update cookie list
setTimeout(function() {
window.location.reload();
}, 1000);
</script>
</head>
<body>
<h2>Cookie List Management</h2>

<!-- Form to set cookies -->


<form action="setCookie.jsp" method="post">
<h3>Set New Cookie</h3>
<table>
<div class="form-group">
<tr><td><label>Cookie Name:</label></td>
<td><input type="text" name="cookieName" required></td>
</tr>
</div>
<div class="form-group">
<tr><td><label>Domain:</label></td>
<td><input type="text" name="domain" required></td></tr>
</div>

<div class="form-group">
<tr><td><label>Max Age (seconds):</label></td>
<td><input type="number" name="maxAge" value="10" required>
</td></tr> </div>
</table>

<input type="submit" value="Add Cookie">


</form>

<hr>

<!-- Display list of set cookies -->


<h3>List of Active Cookies</h3>
<p class="auto-refresh">List updates automatically when cookies expire</p>
<table class="cookie-table">
<thead>
<tr>
<th>Cookie Name</th>
<th>Domain</th>
<th>Max Age (seconds)</th>
</tr>
</thead>
<tbody>
<%
// Get cookie list and current time
@SuppressWarnings("unchecked")
List<Map<String, String>> cookieList = (List<Map<String, String>>)
session.getAttribute("cookieList");
long currentTime = System.currentTimeMillis() / 1000; // Current time in seconds

if (cookieList != null) {
// Remove expired cookies
Iterator<Map<String, String>> iterator = cookieList.iterator();
while (iterator.hasNext()) {
Map<String, String> cookie = iterator.next();
long setTime = Long.parseLong(cookie.get("setTime"));
int maxAge = Integer.parseInt(cookie.get("maxAge"));
if (currentTime > setTime + maxAge) {
iterator.remove(); // Remove expired cookie
continue;
}
}
session.setAttribute("cookieList", cookieList); // Update session with cleaned list
}

if (cookieList != null && !cookieList.isEmpty()) {


for (Map<String, String> cookie : cookieList) {
%>
<tr>
<td><%= cookie.get("name") %></td>
<td><%= cookie.get("domain") %></td>
<td><%= cookie.get("maxAge") %></td>
</tr>
<%
}
} else {
%>
<tr>
<td colspan="3" style="text-align: center;">No active cookies</td>
</tr>
<%
}
%>
</tbody>
</table>
</body>
</html>

<!-- setCookie.jsp -->


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<%@ page import="java.text.SimpleDateFormat" %>
<!DOCTYPE html>
<html>
<head>
<title>Setting Cookie</title>
<style>
.info-box {
margin: 20px;
padding: 15px;
border: 1px solid #ddd;
border-radius: 5px;
background-color: #f9f9f9;
}
.success {
color: green;
}
</style>
</head>
<body>
<div class="info-box">
<%
// Get parameters
String name = request.getParameter("cookieName");
String domain = request.getParameter("domain");
String maxAge = request.getParameter("maxAge");

if (name != null && domain != null && maxAge != null) {


// Get or create cookie list
@SuppressWarnings("unchecked")
List<Map<String, String>> cookieList = (List<Map<String, String>>)
session.getAttribute("cookieList");
if (cookieList == null) {
cookieList = new ArrayList<>();
}

// Get current timestamp


long currentTimeSeconds = System.currentTimeMillis() / 1000;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timestamp = sdf.format(new Date());

// Create new cookie entry


Map<String, String> cookieEntry = new HashMap<>();
cookieEntry.put("name", name);
cookieEntry.put("domain", domain);
cookieEntry.put("maxAge", maxAge);
cookieEntry.put("setTime", String.valueOf(currentTimeSeconds));

// Create actual cookie


Cookie cookie = new Cookie(name, "value");
cookie.setMaxAge(Integer.parseInt(maxAge));
cookie.setDomain(domain);
response.addCookie(cookie);

// Add to list
cookieList.add(cookieEntry);

// Save updated list to session


session.setAttribute("cookieList", cookieList);

// Display cookie set information


%>
<h3 class="success">Cookie Set Successfully</h3>
<p><strong>Cookie Name:</strong> <%= name %></p>
<p><strong>Domain:</strong> <%= domain %></p>
<p><strong>Max Age:</strong> <%= maxAge %> seconds</p>
<p><strong>Set Time:</strong> <%= timestamp %></p>
<%
}
%>
<p><a href="index.jsp">Return to Cookie List</a></p>
</div>
</body>
</html>
o/p

You might also like