Friday, July 6, 2018

Very useful code related to Cookie

Cookie is a small textual information which is sent by web application towards the client in order to remember it. The client (bole toh web browser) stores this information. 
Cookie is very useful to implement shopping cart, to record the client activities, and logging in

For more information about the cookie click here 


## this is the code for "index.jsp" ##

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
//fetch cookies from the client
Cookie[] array = request.getCookies();

String em = "", ps = "";

if(array != null)
{
for(int i = 0; i < array.length; i++)
{
if(array[i].getName().equals("email"))
{
em = array[i].getValue();
}
if(array[i].getName().equals("pass"))
{
ps = array[i].getValue();
}
}
}
%>
<fieldset>
<legend>login</legend>
<form action="login.jsp" method="post">
Email<br>
<input type="email" name="email" value="<%=em%>"><br>
Password<br>
<input type="password" name="pass" value="<%=ps%>"><br>
keep me sign-in<input type="checkbox" name="login" value="tick">
<br>
<input type="submit" value="login">
</form>
</fieldset>
</body>
</html>

## "index.jsp" ends here ##

# # # # # # # # # # # # # # # # # # 

##  this is the code for "demo-cookies.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>Insert title here</title>
</head>
<body>
<%
// fetch all the cookies from the client
Cookie[] array = request.getCookies();

// check if array of cookie is null
       // note: for first client request the array of cookie will be null 
if(array == null) 
{
// create object of cookie
       // here username is name of cookie and naveen is the value for cookie 
Cookie c1 = new Cookie("username","naveen");

// set the age of cookie 'c1'
c1.setMaxAge(3600); // 3600 means cookie will live at client browser for 1 hour  

// send the cookie to the client
response.addCookie(c1);

// show data at client side
out.println("<i>first client visit</i>");
}
        // the client re-visit the jsp again
else 
{
// fetch the data of array of cookie using for loop
for(int i = 0; i < array.length; i++)
{
// fetch the name and value of all the cookies fetched from the client
String name = array[i].getName();
String value = array[i].getValue();

// show data at client side
out.println(name+":"+value+"<br>");
}
}
%>
</body>

</html>

## "demo-cookies.jsp" ends here ##


No comments:

Post a Comment