Fetching cookie value in controller command - IBM WebSphere Commerce
As WebSphere Commerce developers we may sometimes work on scenarios where we need to read a particular cookie value in controller command. Usually lot of developers use cookies as a simple technique to store some value only for a session and when not required to be saved in the database for future use.
Recently, I have came across a business requirement where I have to add a cookie from the front-end (using Javascript) and write some logic in the back-end using the cookie value.
Below is the code I have used to iterate over the list of cookies and fetch the value of the required one in a controller command.
You may be also interested in adding or updating cookie from controller command.
Hope this help someone. If you find any issue in above code or know better alternatives to this code, do share with us through the comment section. Feel free to share this page with your friends and colleagues.
Thanks!
Recently, I have came across a business requirement where I have to add a cookie from the front-end (using Javascript) and write some logic in the back-end using the cookie value.
Below is the code I have used to iterate over the list of cookies and fetch the value of the required one in a controller command.
String cookieName = "MyCookieName";
HttpServletRequest httpServletReq =
((HttpControllerRequestObject) (((ViewCommandContext) getCommandContext()).getRequest()))
.getHttpRequest();
Cookie[] cookies = httpServletReq.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookieName.equals(cookie.getName())) {
System.out.println(cookie.getValue());
break;
}
}
}
You may be also interested in adding or updating cookie from controller command.
Hope this help someone. If you find any issue in above code or know better alternatives to this code, do share with us through the comment section. Feel free to share this page with your friends and colleagues.
Thanks!
Comments
Post a Comment