Cookie Servlet Example

In this example,I am using Cookie with Servlet for Remember User name/Password in login form.Cookies are being are saved for 7 days(3600*24*7),if cookie has been set the form will autofill with the cookies values.

Required Jars

  • jstl-1.2.jar
  • mysql-connector-java-5.0.5.jar

Required Files

  • LoginServlet.java
  • login.jsp
  • web.xml

rememberMe

LoginServlet.java


package com.startwithjava;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L; 
public LoginServlet() {
super(); 
} 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
} 
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String email    = request.getParameter("email");
String password = request.getParameter("password");
int rememberMe =  Integer.parseInt(request.getParameter("rememberMe"));
String name ="";
int userId=0;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/expertwebindia","root","");
Statement st = con.createStatement();
ResultSet rst = st.executeQuery("SELECT * FROM users WHERE email='"+email+"' AND password='"+password+"'");
if(rst!=null){
HttpSession sesion = request.getSession(true);
while(rst.next()){
name = rst.getString("name");
userId = rst.getInt("id");
System.out.println("Id"+userId);
}
sesion.setAttribute("userId", userId);
if(rememberMe==1){

Cookie ck1 = new Cookie("rememberMe","1");
Cookie ck2 = new Cookie("email",email);
Cookie ck3 = new Cookie("password",password);
ck1.setMaxAge(3600*24*7);
ck2.setMaxAge(3600*24*7);
ck3.setMaxAge(3600*24*7);
response.addCookie(ck1);
response.addCookie(ck2);
response.addCookie(ck3);
}

response.sendRedirect("profile");
}
} catch (Exception e) { 
e.printStackTrace();
}
}

}

ProfileServlet.java

package com.startwithjava;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;
public class ProfileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
    public ProfileServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name="";
		String email="";
		HttpSession session =null;
		session = request.getSession(false);
		if(session!=null){
			try {
				int id = Integer.parseInt(session.getAttribute("userId").toString());
				System.out.println("Id"+id);
				Class.forName("com.mysql.jdbc.Driver");
				Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/expertwebindia","root","");
				Statement st = con.createStatement();
				ResultSet rst = st.executeQuery("SELECT * FROM users WHERE id="+id);
				
				while(rst.next()){
				    name  = rst.getString("name");	
				    email = rst.getString("email");
				    System.out.println("email"+email);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			request.setAttribute("name", name);
			request.setAttribute("email", email);
		    RequestDispatcher rd = request.getRequestDispatcher("/profile.jsp");
		    rd.include(request, response);
		}else{
			response.sendRedirect("login.jsp");
		}
	}

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

}

login.jsp

<%@ 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>Cookie Example</title>
</head>
<body>

<h1>Remember Me Cookie Example</h1>

<%
   Cookie cookie = null;
   Cookie[] cookies = null;
   String email="";
   String password="";
   int rememberMe=0;
   String checked="";
   // Get an array of Cookies associated with this domain
   cookies = request.getCookies();
   if( cookies != null ){
      for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; if(cookie.getName().equals("email")){ email = cookie.getValue( ); } if(cookie.getName().equals("password")){ password = cookie.getValue( ); } if(cookie.getName().equals("rememberMe")){ rememberMe = Integer.parseInt(cookie.getValue()); checked="checked"; } } } %>

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

<table>
<tr>
<td>Email</td>
</tr>
<tr>
<td><input type="text" name="email" value="<%=email%>"></td>
</tr>
<tr>
<td>Password</td>
</tr>
<tr>
<td><input type="text" name="password" value="<%=password%>"></td>
</tr>
<tr>
<td><input type="checkbox" name="rememberMe" value="1" <%=checked%>></td>
</tr>
<tr>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>

web.xml

<!--?xml version="1.0" encoding="UTF-8"?--><?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_2_5.xsd" version="2.5">
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.startwithjava.LoginServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>profile</servlet-name>
<servlet-class>com.startwithjava.ProfileServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>profile</servlet-name>
<url-pattern>/profile</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>logout</servlet-name>
<servlet-class>com.startwithjava.LogOutServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>logout</servlet-name>
<url-pattern>/logout</url-pattern>
</servlet-mapping>
</web-app>

Leave a Reply