Skip to content

Instantly share code, notes, and snippets.

@authentical
Created October 1, 2018 09:02
Show Gist options
  • Save authentical/97208e68de1c93402ff3a5f7b3d2922b to your computer and use it in GitHub Desktop.
Save authentical/97208e68de1c93402ff3a5f7b3d2922b to your computer and use it in GitHub Desktop.
// Here I'm learning about javax.servlet.http.Cookie
// TempCookie is just a Cookie implemented with default 60 second maxAge
// TempCookie can be replaced by Cookie
<%@page import="demo.TempCookie"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%
String action;
String submitValue = request.getParameter("submit");
if(submitValue!=null){
action = submitValue;
} else {
action = "";
}
String cookieName=request.getParameter("cookieName");
String cookieValue=request.getParameter("cookieValue");
String isPersistent=request.getParameter("isPersistent");
String message="";
switch(action){
case "Set":
Cookie cookie1 = new TempCookie(cookieName, cookieValue);
if(isPersistent !=null){ cookie1.setMaxAge(2); } // 2 second expiry
response.addCookie( cookie1);
break;
case "Get":
Cookie[] cookieList1 = request.getCookies();
for(Cookie cookie2: cookieList1){
if(cookie2.getName().equals(cookieName)){
cookieValue = cookie2.getValue();
}
}
break;
case "Remove":
// Create a cookie with the same name. Once added to response, it replaces the existing cookie
Cookie cookie3 = new TempCookie(cookieName, "");
cookie3.setMaxAge(0);
response.addCookie(cookie3);
break;
case "Show All":
Cookie[] cookieList2 = request.getCookies();
for(Cookie cookie4: cookieList2){
message += cookie4.getName() + " : " + cookie4.getValue() + "<br/>"; //Should use str bulder
}
break;
default:
break;
}
%>
<!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>Postback form</title>
</head>
<body bgcolor="pink">
<h2>Postback form</h2>
<form method="post">
Name: <input type="text" name="cookieName" value="<%= cookieName%>"><br>
Value: <input type="text" name="cookieValue" value="<%= cookieValue%>"><br><br>
<input type="checkbox" name="isPersistent">Make Persistent<br><br>
<input type="submit" name="submit" value="Set">
<input type="submit" name="submit" value="Get">
<input type="submit" name="submit" value="Remove">
<input type="submit" name="submit" value="Show All">
</form>
<hr/>
<%= message %>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment