Set Cookies from JSP - example

Set Cookies as follows
You may need to add page import
<%@ page language="java" import="java.util.*"%>
<%
Cookie cookie = new Cookie ("username","sanjeewa malalgoda");
cookie.setMaxAge(365 * 24 * 60 * 60);
response.addCookie(cookie);
%>

Get Cookies as Follows
Here we search cookie for name username and display the results
<%
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;
}
}
}
%>
<%
if (myCookie == null)
{
%>No Cookie found with the name <%=cookieName%>
<%
}
else
{
%>
Welcome: <%=myCookie.getValue()%>.
<%
}
%>

No comments:

Post a Comment

Empowering the Future of API Management: Unveiling the Journey of WSO2 API Platform for Kubernetes (APK) Project and the Anticipated Alpha Release

  Introduction In the ever-evolving realm of API management, our journey embarked on the APK project eight months ago, and now, with great a...