Friday, June 21, 2013

Implementing Remember me functionality using Cookies in Java

Hi All,
Welcome to Java-recent.
In this post we will discuss about implementing Remember Me feature in Java web applications.
We would have come across sites where we will have a login form with an option like remember me etc.When we enter credentials and click on this option ,later point return to this page previously  entered credentials will be shown.How did this implementation happen?

One way of implementing this is using Cookies.

Cookie:- is a information sent from server to a browser and gets stored in browsers folder,generally used to maintain state of an user.This data will be sent back to server for subsequent requests

"A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is a small piece of data sent from a website and stored in a user's web browser while a user is browsing a website. When the user browses the same website in the future, the data stored in the cookie is sent back to the website by the browser to notify the website of the user's previous activity." reference from http://en.wikipedia.org/wiki/HTTP_cookie

Cookies are usually transferred in header data

Here we will implement rembember me using functionality using
  • Cookies
  • JSF 2.0
  • Eclipse IDE

Scenario :-
  • We will have a login page with following components
    • UserName text field
    • Password secret input field
    • Submit button
    • Remember me check box
  • A managedbean which will bind these components and perform validations and setting cookies etc.

Source code :-

RememberMe.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!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>Remember me</title>
</head>
<body>
<f:view>
<h:form>
User name<h:inputText value="#{rememberBean.uName }"></h:inputText>
<br>
Password <h:inputSecret value="#{rememberBean.password }"></h:inputSecret>
<br>
<h:commandButton value="Submit" action="#{rememberBean.submit }"></h:commandButton>
<h:selectBooleanCheckbox value="#{rememberBean.checkBox }"></h:selectBooleanCheckbox>Remember me
</h:form>
</f:view>
</body>
</html>

RememberBean.java
@RequestScoped
public class RememberBean {
private String uName;
private String password;
private boolean checkBox=false;
private String virtualCheck;

public RememberBean()
{
isChecked();
}
public String getVirtualCheck() {
return virtualCheck;
}

public void setVirtualCheck(String virtualCheck) {
this.virtualCheck = virtualCheck;
}

public String getuName() {
return uName;
}

public void setuName(String uName) {
this.uName = uName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public boolean isCheckBox() {
return checkBox;
}

public void setCheckBox(boolean checkBox) {
this.checkBox = checkBox;
}

public String submit() {
if (uName != null && password != null) {
FacesContext fc=FacesContext.getCurrentInstance();
if (checkBox == true) {
virtualCheck="true";
//getting current instance of faces context
Cookie cUserName = new Cookie("cUserName", uName);
Cookie cPassword = new Cookie("cPassword", password);
Cookie cVirtualCheck = new Cookie("cVirtualCheck", virtualCheck);
cUserName.setMaxAge(120);
cPassword.setMaxAge(120);
cVirtualCheck.setMaxAge(120);
((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cUserName);
((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cPassword);
((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cVirtualCheck);
}
else
{
virtualCheck="false";
Cookie cVirtualCheck = new Cookie("cVirtualCheck", virtualCheck);
((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cVirtualCheck);
}
}
return "always";
}
public void isChecked()
{
FacesContext fc=FacesContext.getCurrentInstance();
Cookie cookiesArr[]=((HttpServletRequest)(fc.getExternalContext().getRequest())).getCookies();
if(cookiesArr!=null&&cookiesArr.length>0)
for (int i = 0; i < cookiesArr.length; i++) {
String cName=cookiesArr[i].getName();
String cValue=cookiesArr[i].getValue();
System.out.println("---cValue----"+cValue);
if(cName.equals("cUserName"))
{
setuName(cValue);
}else if(cName.equals("cPassword"))
{
setPassword(cValue);
}else if(cName.equals("cVirtualCheck"))
{setVirtualCheck(cValue);
if(getVirtualCheck().equals("false"))
{
setCheckBox(false);
setuName(null);
setPassword(null);
}
else if(getVirtualCheck().equals("true"))
{System.out.println("here in line110");
setCheckBox(true);
}
}
}
{
}
}
}

Explanantion :-
  • submit() method is linked to submit button in RememberMe.jsp
    Here in this method we set the cookies for username,password and check box,if remember me check box is clicked
    Cookie cUserName = new Cookie("cUserName", uName);
    Cookie cPassword = new Cookie("cPassword", password);
    Cookie cVirtualCheck = new Cookie("cVirtualCheck", virtualCheck);
Here we are creating Cookie objects

Below setting age of a cookie in seconds
    cUserName.setMaxAge(24*60*60);
    cPassword.setMaxAge(24*60*60);
    cVirtualCheck.setMaxAge(24*60*60);

Below adding cookies to response
    ((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cUserName);
    ((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cPassword);
    ((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cVirtualCheck);

Then in the bean constructor we are invoking a method called isChecked()

This method will check if already exact cookie is there.If cookies are there then we will retrive their values based on their names and assign it respective fields.
Cookie cookiesArr[]=((HttpServletRequest)(fc.getExternalContext().getRequest())).getCookies();
if(cookiesArr!=null&&cookiesArr.length>0)
for (int i = 0; i < cookiesArr.length; i++) {
String cName=cookiesArr[i].getName();
String cValue=cookiesArr[i].getValue();
System.out.println("---cValue----"+cValue);
if(cName.equals("cUserName"))
{
setuName(cValue);
}else if(cName.equals("cPassword"))
{
setPassword(cValue);
}else if(cName.equals("cVirtualCheck"))
{setVirtualCheck(cValue);
if(getVirtualCheck().equals("false"))
{
setCheckBox(false);
setuName(null);
setPassword(null);
}
else if(getVirtualCheck().equals("true"))
{System.out.println("here in line110");
setCheckBox(true);
}

Ouptput :-

with out checking remember me check box


With checking remember me check box


Note :- in order to save password browser will ask/prompt user to save password or not
Irrespective of Java web technologies and browsers setting and retrieving cookies will play a major role
In eclipse web.xml and faces-config.xml will be automatically created
If we want to delete a cookie,the simplest method is to set its maximum age to zero seconds

Some of the popular posts are :-



Happy Learning

Please provide your valuable comments on this article and share it across your network.



No comments:

Post a Comment

Like and Share