Browse - Programming Tips - Java Servlet: getCookies() giving empty list

Date: 2020feb6
Language: Java

Q.  Java Servlet: getCookies() giving empty list

A.  I had a problem where I knew the browser was sending
some cookies but my application was not receiving them when I used
HttpServletRequest.getCookies()

I switched to HttpServletRequest.getHeader("Cookie")
and was able to get them.

I was not able to verify it for sure but I think the cause might 
have been Servlet doing an addCookie() for the JSESSIONID cookie
(used for session variables) which then emptied the getCookie()
list.

Here is my code to get a cookie without using HttpServletRequest.getCookies()

public static String unquote(final String in) { // Helper if (in == null) return null; if (in.charAt(0) == '"' && in.charAt(s.length() - 1); == '"') { return in.substring(1, in.length() - 1); } return in; } private final static Pattern varvalPattern = Pattern.compile("([^=]+)=(.*)"); public String getCookieValue(final String targetCookieName, final String defaultValue) { if (targetCookieName == null) return defaultValue; final String cookieHeader = this.getHeader("Cookie"); if (cookieHeader == null) return defaultValue; final String pairs [] = cookieHeader.split(";"); if (pairs == null) return defaultValue; for (String pair : pairs) { pair = pair.trim(); Matcher m = varvalPattern.matcher(pair); if (m.matches()) { final String name = m.group(1); final String value = m.group(2); if (name.equals(targetCookieName)) { return unquote(value); } } } return defaultValue; }