Servlet Application Sessions Cookies Example
Servlet Application Sessions Cookies Example
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.
---
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>
<label for="username">Username:</label>
<label for="password">Password:</label>
<button type="submit">Login</button>
</form>
</body>
</html>
This servlet handles login, creates a session, and optionally sets a cookie if
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
session.setAttribute("username", username);
loginCookie.setMaxAge(24 * 60 * 60);
response.addCookie(loginCookie);
response.sendRedirect("BookingServlet");
} else {
response.setContentType("text/html");
again.</h3></body></html>");
request.getRequestDispatcher("index.html").include(request, response);
This servlet allows a logged-in user to book a ticket. It uses the session to
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
} else {
if (cookies != null) {
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");
out.println("<html><body>");
out.println("<label for='destination'>Destination:</label>");
out.println("</form>");
type='submit'>Logout</button></form>");
out.println("</body></html>");
session.getAttribute("username") : null;
if (username == null) {
response.sendRedirect("index.html");
} else {
response.setContentType("text/html");
out.println("<html><body>");
out.println("</body></html>");
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
if (session != null) {
session.invalidate();
loginCookie.setMaxAge(0);
response.addCookie(loginCookie);
response.setContentType("text/html");
out.</h3></body></html>");
response.sendRedirect("index.html");
---
Explanation:
username attribute.
username.
cookie.