Cookies in JSP

In world wide web the protocol we use is a http protocol. What are Cookies in JSP and How to manage it programmatically through JSP code.

Cookies in JSP

Cookies in JSP

        

In world wide web the protocol we use is a http protocol. The Http protocol is a stateless protocol means that it can't keep a state i.e. it can't persist values. To maintain a session we used the concept of cookies.

When cookie based session management is used, a token is generated which contains user's information, is sent to the browser by the server. The cookie is sent back to the server when the user sends a new request. By this cookie, the server is able to identify the user. In this way the session is maintained. Cookie is nothing but a name- value pair, which is stored on the client machine. By default the cookie is implemented in most of the browsers. If we want then we can also disable the cookie. For security reasons, cookie based session management uses two types of cookies.

1) Non- secure session cookie: This cookie can flow between the browser and server under the SSL or non- SSL connection.

2) Secure authentication cookie: It is used to authenticate the data. This cookie flow over SSL. This type of authenication cookie are used where the information security is very important.

The code of the program is given below:

<%@ page language="java"  %>
<html>
<head>
<title>Cookie Input Form</title>
</head>
<body>
<form method="get" action="SettingCookie.jsp">
<p><b>Enter Your Name: </b><input type="text" name="username"><br>
<input type="submit" name = "submit" value="Submit">

</form>

</body>

 

<%@ page language="java"%>
<%
String username=request.getParameter("username");
if(username==null) username="";
Cookie cookie = new Cookie ("username",username);
cookie.setMaxAge(60 * 60);
response.addCookie(cookie);
%>
<html>
<head>
<title>Cookie Saved</title>
</head>
<body>
<p><a href="GettingCookie.jsp">Click here to see the cookie value</a><p>

</body>

 

<%@ page language="java"  %>
<%
String cookieName = "username";
Cookie cookies [] = request.getCookies ();
Cookie myCookie = null;
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++) 
{
if (cookies [i].getName().equals (cookieName))
{
myCookie = cookies[i];
break;
}
}
}
%>
<html>
<head>
<title>Show Saved Cookie</title>
</head>
<body>

<%
if (myCookie == null) {
%>
No Cookie found with the name <%=cookieName%>
<%
} else {
%> 
<p>Welcome: <%=myCookie.getValue()%>.
<%
}
%>
</body>

The output of the program is given below:

 

Download this example: