Servlet Applications with Cookies and Sessions
1. Cookies
Definition
A Cookie is a small text file stored in the user's browser by the server. It helps remember information
such as username, language, or login status.
Syntax
Cookie cookie = new Cookie("username", "Arshi");
[Link](cookie);
2. Session
Definition
A Session stores user data on the server. Each user gets a unique Session ID.
Creating a Session
HttpSession session = [Link]();
[Link]("username", "Arshi");
Using RequestDispatcher Interface, create a Servlet that validates the password entered by the user. If
the password is "Servlet", forward the user to WelcomeServlet; otherwise, stay on the [Link]
page and display an error message.
Step 1: Create Dynamic Web Project
Open Eclipse
File → New → Dynamic Web Project
Project Name:
RequestDispatcherApp
Target Runtime:
Apache Tomcat v11
Click Finish.
Step 2: Create HTML File
Go to
src/main/webapp
Right Click
New → HTML File
File Name:
[Link]
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<h2>Login Form</h2>
<form action="ValidateServlet" method="post">
Password:
<input type="password" name="password" required>
<br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
Step 3: Create Package
Go to
src/main/java
Right Click
New → Package
Package Name
[Link]
Click Finish.
Step 4: Create ValidateServlet
Right Click package
New → Servlet
Servlet Name
ValidateServlet
Click Finish.
Replace the generated code with:
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/ValidateServlet")
public class ValidateServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
String password = [Link]("password");
if([Link]("Servlet")) {
RequestDispatcher rd =
[Link]("WelcomeServlet");
[Link](request, response);
else {
[Link]("<font color='red'>Invalid Password</font><br>");
RequestDispatcher rd =
[Link]("[Link]");
[Link](request, response);
Step 5: Create WelcomeServlet
Right Click package
New → Servlet
Servlet Name
WelcomeServlet
Click Finish.
Replace the code with:
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html>");
[Link]("<body>");
[Link]("<h2>Welcome User</h2>");
[Link]("</body>");
[Link]("</html>");
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
Step 6: Project Structure
RequestDispatcherApp
├── Java Resources
│ └── src/main/java
│ └── [Link]
│ ├── [Link]
│ └── [Link]
└── src/main/webapp
└── [Link]
Step 7: Run the Project
1. Right Click RequestDispatcherApp
2. Select
Run As → Run on Server
3. Choose
Tomcat v11.0 Server
4. Click Finish.
Step 8: Open Browser
Open:
[Link]
Output 1 (Correct Password)
Enter:
Servlet
Click Login.
Output:
Welcome User
Output 2 (Wrong Password)
Enter:
abc123
Click Login.
Output:
Invalid Password
Password: __________
[Login]
The user stays on the [Link] page and sees the error message.
RequestDispatcher Methods Used
forward()
RequestDispatcher rd = [Link]("WelcomeServlet");
[Link](request, response);
Purpose: Transfers the request to WelcomeServlet.
include()
RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);
Purpose: Displays the contents of [Link] along with the error message, allowing the user to try
again.
Q1. What is RequestDispatcher?
Answer: RequestDispatcher is an interface used to forward a request to another resource or include the
output of another resource in the current response.
Q2. What is the difference between forward() and include()?
forward() transfers the request completely to another resource.
include() includes the output of another resource while continuing the current response.
Q3. Why is include() used when the password is wrong?
Answer: It displays the login page again together with the "Invalid Password" message so that the user
can enter the password again.
Create a Servlet that Uses Cookies to Store the Number of Times a User Has Visited the Servlet
Objective
Create a Java Servlet that uses Cookies to count how many times a user has visited the servlet.
Step 1: Create Dynamic Web Project
Open Eclipse
File → New → Dynamic Web Project
Project Name:
CookieApp
Target Runtime:
Apache Tomcat v11
Click Finish.
Step 2: Create Package
Go to
src/main/java
Right Click
New → Package
Package Name:
[Link]
Click Finish.
Step 3: Create Servlet
Right Click package
New → Servlet
Servlet Name:
VisitServlet
Click Finish.
Step 4: Replace the Code
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/VisitServlet")
public class VisitServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
int count = 1;
Cookie[] cookies = [Link]();
if (cookies != null) {
for (Cookie c : cookies) {
if ([Link]().equals("visitCount")) {
count = [Link]([Link]());
count++;
}
Cookie cookie = new Cookie("visitCount", [Link](count));
[Link](60 * 60 * 24);
[Link](cookie);
[Link]("<html><body>");
[Link]("<h2>Welcome!</h2>");
[Link]("<h3>You have visited this page " + count + " times.</h3>");
[Link]("</body></html>");
Step 5: Project Structure
CookieApp
src/main/java
|-- [Link]
| |
| |-- [Link]
src/main/webapp
Step 6: Run the Project
Right Click Project
Run As
Run on Server
Choose
Tomcat v11
Click Finish.
Step 7: Open Browser
[Link]
Expected Output
First Visit
Welcome!
You have visited this page 1 time.
Second Visit (Refresh)
Welcome!
You have visited this page 2 times.
Third Visit
Welcome!
You have visited this page 3 times.
Every time you refresh the page, the visit count increases.
How It Works
Read Cookies
Cookie[] cookies = [Link]();
Gets all cookies from the browser.
Check Cookie
if([Link]().equals("visitCount"))
Checks whether the cookie named visitCount exists.
Read Cookie Value
count = [Link]([Link]());
Reads the previous visit count.
Increase Count
count++;
Adds 1 to the visit count.
Create Cookie
Cookie cookie = new Cookie("visitCount",
[Link](count));
Creates a cookie with the updated count.
Store Cookie
[Link](cookie);
Sends the cookie to the browser.
Display Count
[Link]("<h3>You have visited this page " + count + " times.</h3>");
Shows the number of visits on the web page.
Output Example
First Visit
Welcome!
You have visited this page 1 time.
Second Visit
Welcome!
You have visited this page 2 times.
Fifth Visit
Welcome!
You have visited this page 5 times.
Viva Questions
Q1. What is a Cookie?
Answer:
A Cookie is a small piece of data stored in the user's browser. It is used to remember information such as
login status, user preferences, or visit count.
Q2. Which class is used for Cookies?
Answer:
[Link]
Q3. How do you create a Cookie?
Cookie cookie = new Cookie("visitCount","1");
Q4. How do you send a Cookie to the browser?
[Link](cookie);
Q5. How do you read Cookies?
Cookie[] cookies = [Link]();
Q6. Why is setMaxAge() used?
[Link](60*60*24);
It sets the cookie's lifetime. Here, the cookie is stored for 1 day (24 hours).
Servlet Program Using Session Creation and Destruction
Aim
Create a Servlet demonstrating the use of Session Creation and Session Destruction. Also check whether
the user has visited the page for the first time or has visited earlier using HttpSession.
Step 1: Create Dynamic Web Project
Open Eclipse
File → New → Dynamic Web Project
Project Name:
SessionApp
Target Runtime:
Apache Tomcat v11
Click Finish.
Step 2: Create Package
Go to
src/main/java
Right Click
New → Package
Package Name
[Link]
Step 3: Create VisitServlet
Right Click Package
New → Servlet
Servlet Name
VisitServlet
Replace the generated code with:
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/VisitServlet")
public class VisitServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
HttpSession session = [Link]();
Integer count = (Integer) [Link]("count");
if(count == null)
count = 1;
[Link]("<h2>Welcome! This is your first visit.</h2>");
else
count++;
[Link]("<h2>Welcome Back!</h2>");
[Link]("count", count);
[Link]("<h3>Visit Count : " + count + "</h3>");
[Link]("<br><a href='LogoutServlet'>Logout</a>");
}
}
Step 4: Create LogoutServlet
Right Click Package
New → Servlet
Servlet Name
LogoutServlet
Replace the generated code with:
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/LogoutServlet")
public class LogoutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
HttpSession session = [Link](false);
if(session != null)
[Link]();
[Link]("<h2>Session Destroyed Successfully</h2>");
[Link]("<a href='VisitServlet'>Visit Again</a>");
Step 5: Project Structure
SessionApp
├── Java Resources
│ └── src/main/java
│ └── [Link]
│ ├── [Link]
│ └── [Link]
└── src/main/webapp
Step 6: Run the Project
Right Click Project
Run As
Run on Server
Select
Tomcat v11
Click Finish.
Step 7: Open Browser
[Link]
Output
First Visit
Welcome! This is your first visit.
Visit Count : 1
Logout
Refresh the Page
Welcome Back!
Visit Count : 2
Logout
Again Refresh
Welcome Back!
Visit Count : 3
Logout
Click Logout
Session Destroyed Successfully
Visit Again
Click Visit Again
Welcome! This is your first visit.
Visit Count : 1
How the Program Works
Create Session
HttpSession session = [Link]();
Creates a new session if one does not already exist.
Get Session Data
Integer count = (Integer) [Link]("count");
Reads the visit count stored in the session.
Store Data in Session
[Link]("count", count);
Stores the updated visit count.
Destroy Session
[Link]();
Destroys the current session and removes all session data.
Viva Questions
Q1. What is a Session?
Answer:
A Session is used to store user-specific information on the server. It allows the server to remember a user
across multiple requests.
Q2. Which class is used for Session?
HttpSession
Q3. How do you create a Session?
HttpSession session = [Link]();
Q4. How do you store data in a Session?
[Link]("count", count);
Q5. How do you retrieve data from a Session?
Integer count = (Integer) [Link]("count");
Q6. How do you destroy a Session?
[Link]();
Q7. Difference Between Cookies and Sessions
Cookies Sessions
Stored in the client's browser Stored on the server
Less secure More secure
Limited storage Can store larger amounts of data
Managed using the Cookie class Managed using the HttpSession interface