This tutorial explains how to create and login logout code using stateless client based session cookie.
Environment used:
Eclipse luna
Jdk 1.8
Servlet 2.5 web module
Tomcat 8 (require servlet 3.1 jar)
Step 1:
Create a simple login page login.html
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <form action="login1" method="post"> User:<br/><input type="text" name="user"/><br/> Password:<br/><input type="password" name="password"/><br/> <input type="submit" value="Login"/> </form> </body> </html>
Step 2:
Create a Login Servlet (Login.java).
This servlet will
1. Authenticate the user (username: candidjava , password: candidjava)
2. create new cookie object
3. redirect to home page
If the username password is invalid it will redirect to login.html with an error message.
package com.candidjava.servlet.cookie; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Login extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String un = request.getParameter("uname"); String pw = request.getParameter("pass"); PrintWriter out = response.getWriter(); Cookie ck = new Cookie("auth", un); ck.setMaxAge(600); if (un.equals("candidjava") & pw.equals("candidjava")) { response.addCookie(ck); response.sendRedirect("home.jsp"); return; } else { RequestDispatcher rd = request.getRequestDispatcher("login.html"); out.println("Either user name or password is wrong."); rd.include(request, response); } } }
Step 3:
home.jsp
This page will be loaded after successful login, and it will automatically logged out if the session time exceeds 10min or if user deleted all cookie from the browser
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <% Cookie[] cks = request.getCookies(); if (cks != null) { for (int i = 0; i < cks.length; i++) { String name = cks[i].getName(); String value = cks[i].getValue(); if (name.equals("auth")) { break; // exit the loop and continue the page } if (i == (cks.length - 1)) // if all cookie are not valid redirect to error page { response.sendRedirect("sessionExpired.html"); return; // to stop further execution } i++; } } else { response.sendRedirect("sessionExpired.html"); return; // to stop further execution } %> <h3>You had successfully logged in.</h3> <br> your session is set to expire in 10min <br> try reloading after 10 min <br> <form action="Logout" method="post"> <input type="submit" value="Logout"> </form> </body> </html>
Step 4:
web.xml mapping
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Struts 2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
Screen shot
Download Example
War file : cookie example
Zip file : Cookie example