JSP

JSP Projects

JSP Project

Handle the cookie in JSP page
Previous Home Next

 

In this page of the tutorials we are going to show you that how to handle cookies in JSP pages. In this tutorial we will be learn how to add cookies through jsp page and then show the value of the same cookie in another JSP page

 getMaxAge() It is return the maximum specified age of the cookie 
getName() It is used to return the name of the cookie
getValue() It is used to return the value of the cookie

 

===================================testcookie.jsp=========================================

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Cookie Form</title>
</head>
<body>
<form method="post" action="cookiesset.jsp">
<p><b>Enter Your Name: </b><input type="text" name="username"><br>
<input type="submit" value="Submit">

</form>

</body>
</html>

====================================cookiesset.jsp===================================

<%@ 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="showcookiesvalue.jsp">Next Page to view the cookie value</a><p>

</body>
</html>

====================================showcookiesvalue.jsp===================================

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


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

Previous Home Next