0% found this document useful (0 votes)
12 views9 pages

Servlet Application Sessions Cookies Example

This document provides a complete Java web application example that demonstrates the use of sessions and cookies in a servlet-based login and ticket booking system. It includes components such as a login form (index.html), a LoginServlet for handling user authentication and session management, a BookingServlet for ticket booking, and a LogoutServlet for logging out users. The application ensures that only logged-in users can access the booking functionality and remembers users through cookies if they choose to be remembered.
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)
12 views9 pages

Servlet Application Sessions Cookies Example

This document provides a complete Java web application example that demonstrates the use of sessions and cookies in a servlet-based login and ticket booking system. It includes components such as a login form (index.html), a LoginServlet for handling user authentication and session management, a BookingServlet for ticket booking, and a LogoutServlet for logging out users. The application ensures that only logged-in users can access the booking functionality and remembers users through cookies if they choose to be remembered.
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/ 9

Complete Java Web Application Example: Sessions and Cookies

Here is a complete Java web application example demonstrating how to use

sessions and cookies in a servlet-based

login and ticket booking system. This code covers:

1. Login Handling: A form for users to log in.

2. Session Management: Tracking logged-in users using sessions, allowing

access to the booking page only for logged-in users.

3. Session Data Usage: Storing and retrieving user information in the session.

4. Cookies Usage: Storing a login cookie to remember the user for a future

session.

The project structure consists of three main parts:

1. index.html - Login form.

2. LoginServlet - Validates login, manages the session, and sets a cookie.

3. BookingServlet - Allows the user to book a ticket if logged in.

---

1. index.html - Login Form

This page provides a simple login form. Once logged in, the user can access
the booking page.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Login</title>

</head>

<body>

<h2>Login Page</h2>

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

<label for="username">Username:</label>

<input type="text" name="username" required><br><br>

<label for="password">Password:</label>

<input type="password" name="password" required><br><br>

<input type="checkbox" name="rememberMe"> Remember Me<br><br>

<button type="submit">Login</button>

</form>

</body>
</html>

2. LoginServlet.java - Handling Login, Session, and Cookies

This servlet handles login, creates a session, and optionally sets a cookie if

"Remember Me" is checked.

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class LoginServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse

response) throws ServletException, IOException {

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

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

String rememberMe = request.getParameter("rememberMe");

if ("user".equals(username) && "password".equals(password)) {

HttpSession session = request.getSession();

session.setAttribute("username", username);

if (rememberMe != null && rememberMe.equals("on")) {


Cookie loginCookie = new Cookie("username", username);

loginCookie.setMaxAge(24 * 60 * 60);

response.addCookie(loginCookie);

response.sendRedirect("BookingServlet");

} else {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html><body><h3>Invalid login. Please try

again.</h3></body></html>");

request.getRequestDispatcher("index.html").include(request, response);

3. BookingServlet.java - Ticket Booking with Session and Cookies

This servlet allows a logged-in user to book a ticket. It uses the session to

check if the user is logged in.

It also retrieves the username from a cookie if available.

import javax.servlet.*;

import javax.servlet.http.*;
import java.io.*;

public class BookingServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse

response) throws ServletException, IOException {

HttpSession session = request.getSession(false);

String username = null;

if (session != null && session.getAttribute("username") != null) {

username = (String) session.getAttribute("username");

} else {

Cookie[] cookies = request.getCookies();

if (cookies != null) {

for (Cookie cookie : cookies) {

if (cookie.getName().equals("username")) {

username = cookie.getValue();

session = request.getSession();

session.setAttribute("username", username);

break;

}
}

if (username == null) {

response.sendRedirect("index.html");

} else {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

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

out.println("<h3>Welcome, " + username + "!</h3>");

out.println("<h2>Book Your Ticket</h2>");

out.println("<form action='BookingServlet' method='post'>");

out.println("<label for='destination'>Destination:</label>");

out.println("<input type='text' name='destination' required><br><br>");

out.println("<button type='submit'>Book Ticket</button>");

out.println("</form>");

out.println("<form action='LogoutServlet' method='post'><button

type='submit'>Logout</button></form>");

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

protected void doPost(HttpServletRequest request, HttpServletResponse

response) throws ServletException, IOException {


HttpSession session = request.getSession(false);

String username = (session != null) ? (String)

session.getAttribute("username") : null;

if (username == null) {

response.sendRedirect("index.html");

} else {

String destination = request.getParameter("destination");

response.setContentType("text/html");

PrintWriter out = response.getWriter();

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

out.println("<h3>Ticket booked successfully!</h3>");

out.println("<p>Username: " + username + "</p>");

out.println("<p>Destination: " + destination + "</p>");

out.println("<a href='BookingServlet'>Back to Booking Page</a>");

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

4. LogoutServlet.java - Logging Out


The LogoutServlet handles logging out by invalidating the session and deleting

the login cookie.

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class LogoutServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse

response) throws ServletException, IOException {

HttpSession session = request.getSession(false);

if (session != null) {

session.invalidate();

Cookie loginCookie = new Cookie("username", "");

loginCookie.setMaxAge(0);

response.addCookie(loginCookie);

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html><body><h3>You have been logged

out.</h3></body></html>");
response.sendRedirect("index.html");

---

Explanation:

1. Login: LoginServlet checks credentials and creates a session with a

username attribute.

2. Booking: BookingServlet checks if the session or cookie contains a

username.

3. Logout: LogoutServlet invalidates the session and removes the username

cookie.

You might also like