2012-02-23

Setting & getting web browser cookies

Details here.

Client-side JavaScript/ ECMAScript:

function createCookie(name, value, days){
  if (days){
    var date = new Date()
    date.setTime(date.getTime()+(days*24*60*60*1000))
    var expires = "; expires="+date.toGMTString()
  }
  else var expires = ""
  document.cookie = name+"="+encodeURIComponent(value)+expires+"; path=/"
}
createCookie("best_location", "/this folder; it's short + great!", 3650)

Server-side Java in JSP using Liferay:

<%@page import="com.liferay.portal.kernel.util.HtmlUtil" %>
<%@page import="java.net.URLDecoder" %>
<%
Cookie cookies[] = request.getCookies();
if (cookies != null){
  for (Cookie cookie : cookies){
    if (cookie.getName().equals("best_location")) out.print("Best location: " + HtmlUtil.escape(URLDecoder.decode(cookie.getValue())));
  }
}
%>