0

I have three cookies, two of them are used to keep the details of user (name and id) and the other one is to keep the type of user. I need to show a specific message based on type of user which is retrieved from one of the cookies.

I have the following working code but it is a bit complex, I am wondering if there is any efficient way to do it.

<c:forEach items="${cookie}" var="IdCookie">
     <c:if test="${IdCookie.key == 'UserID'}">   << if UserID cookie is found

            <c:forEach items="${cookie}" var="nameCookie">

               <c:if test="${nameCookie.key == 'User'}"> << if User cookie is found

                      <p>${IdCookie.value.value} &nbsp; ${nameCookie.value.value}</p>
                      <c:forEach items="${cookie}" var="typeCookie">                                     
                                <c:if test="${typeCookie.key == 'Type'}"> << if Type cookie is found

                                     <c:if test="${typeCookie.value == 'One'}">
                                         <p>,Your type is one </p>
                                     </c:if>
                                     <c:if test="${typeCookie.value == '0'}">
                                         <p>,Your type is NOT one </p>
                                      </c:if>

                                 </c:if>

                      </c:forEach>
               </c:if>

             </c:forEach>
     </c:if>

 </c:forEach>

Output

   Cookies' values >> 1 Alex 0
   output >> 1 Alex,Your type is Not one 
   Cookies' values >>  1 Jack One
   output >> 1 Jack,Your type is one 
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
AlexCartio1
  • 238
  • 3
  • 9
  • 29
  • 1
    first thing is to have separate for loops for each part of your output to make it simpler. – J888 Feb 27 '14 at 09:03

1 Answers1

1

See Getting cookie in JSP

You can make this a lot simpler this way:

<p>${cookie['UserId'].value} ${cookie['User'].value}, 
<c:if test="${cookie['Type'].value == 'One'}">
  ,Your type is one
</c:if>
<c:if test="${cookie['Type'].value == '0'}">
  ,Your type is NOT one
</c:if></p>

Making it even simpeler by using the ternary operator (?:) is left an an exercise for the reader :).

If you want to check if the cookie exists first, see this one: Check if Cookie exists with JSP EL

so you could do:

<c:if test="${fn:contains(header.cookie, 'User=') and fn:contains(header.cookie, 'Type=') and fn:contains(header.cookie, 'UserId=')}">

When this gets to complex, I would advise to wrap it in a bean though.

Community
  • 1
  • 1
Joeri Hendrickx
  • 16,947
  • 4
  • 41
  • 53