Java, .NET, PHP, PYTHON, ANGULAR, ML, Data Science, Testing, CI Tutorials in Easy Languages.

"Best Software Training, Internship, Project Development center of Indore India, Helpline 780506-3968"

Cookie Tutorial in Java Web Application, Cookies Tutorial in JSP and Servlet:-


A cookie in Java Web Application:- 

 It is used to store application data under the browser cookies folder which can be used to store application information in the client machine. cookie always will be created into client machine and use system memory but session always will be created by server-side and use server memory to contain application but by default session data also managed by cookie.

Remember me option is the best example of a cookie because when we click on the remember me option under application then userid and password will be stored into the cookie folder of a particular web browser means chrome and firefox cookie folder will be different.

Java provides a cookie class to store information under the cookie. cookie syntax is common for JSP and Servlet.

Set data on Cookie Folder:-

Cookie ref = new Cookie("key","value");
response.addCookie(ref);
ref.setMaxAge(time);

Get data from the cookie folder

Cookie arrayname[] = request.getCookies();


Example of Cookie to set and Get data:-

1)  Create a JSP Web page:-

<%@ 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>
<%
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Expires","0");
response.setDateHeader("Expires",-1);

%>

</head>
<body>
<%
String uname="";
String upass="";
if(request.getCookies()!=null)
{
Cookie arr[] = request.getCookies();

for(int i=0;i<arr.length;i++)
{
if(arr[i].getName().equals("cd"))
     {
         uname=arr[i].getValue();
     }
     if(arr[i].getName().equals("pw"))
     {
         upass=arr[i].getValue();
     }
}

}
%>
<form action="AdminLoginSer" method="post">
            <p><input type="text" name="txtuser" value="<%= uname %>" placeholder="Enter username" /></p>
            <p><input type="password" name="txtpass" value="<%= upass %>" placeholder="Enter password" /></p>
            <p><input type="checkbox" name="chk" value="remember" />Remember me</p>
            <p><input type="submit" name="btnsubmit" value="Login" /> </p>
        </form>
        
 <%
 if(request.getParameter("error")!=null)
 {
out.print(request.getParameter("error"));
 }
 
 
 
 %>       
</body>


Code of Login Servlet:-

package admin;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

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;

import dao.Datahelper;

/**
 * Servlet implementation class AdminLoginSer
 */
@WebServlet("/AdminLoginSer")
public class AdminLoginSer extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
try {
Datahelper.connection();
ResultSet res=Datahelper.dqlOPe("select * from admin where username='"+request.getParameter("txtuser")+"' and password='"+request.getParameter("txtpass")+"'");
if(res.next())
{
HttpSession session = request.getSession();
if(request.getParameter("chk")!=null)
{
Cookie c1 = new Cookie("cd",request.getParameter("txtuser"));
c1.setMaxAge(10000);
response.addCookie(c1);
Cookie c2 = new Cookie("pw",request.getParameter("txtpass"));
c2.setMaxAge(10000);
response.addCookie(c2);
}
session.setAttribute("uid",request.getParameter("txtuser"));
response.sendRedirect("databaseui/databaseinsertion.jsp");
}
else
{
response.sendRedirect("index.jsp?error=invalid userid and password");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}


Code of logout.jsp
<%

Cookie arr[] = request.getCookies();
for(int i=0;i<arr.length;i++)
{
 
if(arr[i].getName().equals("cd"))
     {
Cookie cuid = arr[i];
cuid.setPath("/Advancejava");
cuid.setMaxAge(0);
cuid.setValue("");
 
 
         response.addCookie(cuid);
         out.println(arr[i].getName()) ;
         out.println(arr[i].getValue()) ;
     }
if(arr[i].getName().equals("pw"))
     {
 
Cookie pw = arr[i];
pw.setPath("/Advancejava");
pw.setMaxAge(0);
pw.setValue("");
 
 
         response.addCookie(pw);
         out.println(arr[i].getName()) ;
         out.println(arr[i].getValue()) ;
     }
 
}

session.removeAttribute("uid");
session.invalidate();
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Expires","0");
response.setDateHeader("Expires",-1);

response.sendRedirect("../index.jsp");



%>

</html>

Post a Comment

POST Answer of Questions and ASK to Doubt

Previous Post Next Post