Expand my Community achievements bar.

Dive into Adobe Summit 2024! Explore curated list of AEM sessions & labs, register, connect with experts, ask questions, engage, and share insights. Don't miss the excitement.

Java vs Javascript: getting different values for browser cookie

Avatar

Level 8

So I have the following Java

for (Cookie cookie : getRequest().getCookies()) {

   if (cookie.getName().equals((String) Constants.class.getDeclaredField(get('mycookie',String.class)).get(null))) {

   value = cookie.getValue();

  }

}

and it's returning some value to my HTL

<sly data-sly-use.courseBookmarkCookie1="${'com.myhost.core.impl.view.components.GetCookieHelper}"></sly>

<p id="doccookiejava">bookmark cookie (from java): ${courseBookmarkCookie1.value}</p>

The problem is when I do the same thing using javascript,

<script type="text/javascript">

    $(document).ready(function(){

        console.log(document.cookie);

    });

</script>

I've encountered instances (on page refresh) where the cookie from Java is empty while document.cookie (from javascript) has a value and vice versa.

Any ideas on how to fix it? or perhaps anything I should be looking at?

I am not seeing the same issue when viewing the page on my local instance of AEM.

Thanks!

edit: I've tried my page on author and publisher (view as published) and they are working fine. seems the behavior happens when using the dispatcher.

2 Replies

Avatar

Community Advisor

I think it might be happening because the pages are cached in dispatcher and java file will not be executed once the page is cached in dispatcher. Javascript will execute on browser so always get the latest cookie value.

In order to read the value in java, page should not be cached in dispatcher but it will have performance issues as everytime it will hit publisher.

Hope it gives some idea related to your issue.

Avatar

Level 8

but cookies (at least document.cookies) are supposed to be stored in the device.