Skip to content

Instantly share code, notes, and snippets.

@raunakhajela
Created January 12, 2018 13:54
Show Gist options
  • Save raunakhajela/bd7ee39b6c8597b9e0dbbff5f53f9bdd to your computer and use it in GitHub Desktop.
Save raunakhajela/bd7ee39b6c8597b9e0dbbff5f53f9bdd to your computer and use it in GitHub Desktop.
JSP: Cookies
<html>
<head></head>
<body>
<h3>Training</h3>
<%
//the default..if there are no cookies
String favlang = "Java";
//get the cookies from the browser request
Cookie[] theCookies = request.getCookies();
//find our favlang cookie
if(theCookies != null){
for(Cookie tempCookie : theCookies){
if("myApp.favlang".equals(tempCookie.getName())){
favlang = tempCookie.getValue();
break;
}
}
}
%>
<!-- now show a personalised page -->
<!-- show new books for this lang -->
<h4>New books for <%= favlang %></h4>
<ul>
<li>blah blah blah blah</li>
<li>blah blah blah blah</li>
<li>blah blah blah blah</li>
<li>blah blah blah blah</li>
</ul>
<hr>
<a href="cookies-personalize-form.html">Personalise this page</a>
</body>
</html>
<html>
<head></head>
<%
//read form data
String favlang = request.getParameter("favlang");
//create the cookie
Cookie theCookie = new Cookie("myApp.favlang", favlang);
//set the life span..total no of seconds
theCookie.setMaxAge(60*60*24*365);
//send cookie to browser
response.addCookie(theCookie);
%>
<body>
Thanks! We set your fav lang to: ${param.favlang}
<br><br>
<a href="cookies-homepage.jsp">Return to home</a>
</body>
</html>
<!--
- keep track of user preferences even when they close the browser
- personalize a web site for a user
-->
<html>
<body>
<form action="cookies-personalise-response.jsp">
Select fav language:
<select name="favlang">
<option>C</option>
<option>C++</option>
<option>C#</option>
<option>PHP</option>
</select>
<input type="submit" value="Submit">
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment