JSP Cookies
 
Example Using Cookies
 
No we will write code in JSP file to set and then display the cookie.
 
Create Form
Here is the code of the form (cookieform.jsp) which prompts the user to enter his/her name.
 
<%@ page language="java" %>

<html>

<head>

<title>Cookie Input Form</title>
</head>

<body>
<form method="post" action="setcookie.jsp">
<p><b>Enter Your Name: </b><input type="text" name="username"><br>
<input type="submit" value="Submit">

</form>

</body>

<html>
 
Above form prompts the user to enter the user name. User input are posted to the setcookie.jsp file, which sets the cookie.
Output
 
Here is the code of setcookie.jsp file:
 
<%@ page language="java" import="java.util.*"%>
<%
String username=request.getParameter("username");
if(username==null) username="";


Date now = new Date();
String timestamp = now.toString();
Cookie cookie = new Cookie ("username",username);
cookie.setMaxAge(365 * 24 * 60 * 60);
response.addCookie(cookie);

%>

<html>

<head>

<title>Cookie Saved</title>

</head>
<body>

<p><a href="showcookievalue.jsp">Next Page to view the cookie value</a><p>

</body>

<html>
Above code sets the cookie and then displays a link to view cookie page.
Output
 
Here is the code of display cookie page (showcookievalue.jsp):
 
<%@ 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>

<html>
When user navigates to the above the page, cookie value is displayed.
Output