Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read cookies with JSTL

Tags:

jsp

cookies

jstl

I was studying about cookies and was able to create and read them using scriptlet-based JSP,however when I tried to do the same using JSTL it's not displaying all my cookies, only "JSESSIONID ..." and with my other project it shows the cookie that I created. My question here is why, it seems right for me but not for my browser.. Here is what I'm trying to do using JSTL:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:forEach var="cookieVal" items="${requestScope.cookies}" > 
    <tr>
        <td align="right">${cookieVal.name}</td>
        <td>${cookieVal.value}</td>
    </tr>
</c:forEach>

And my other project working:

<% Cookie[] cookies = request.getCookies();
for (int i = 0; i < cookies.length; i++) {
    Cookie cookie = cookies[i];%>
    <tr>
        <td><%=cookie.getName()%></td>
        <td><%=cookie.getValue()%></td>
    </tr>
<%}%>

And I have m JSTL .jars inside my project libraries folder... Thank you!

like image 359
migmig Avatar asked Nov 18 '25 22:11

migmig


2 Answers

You can access cookie value named cookeName by ${cookie.cookieName.value}

like image 53
zhaoyou Avatar answered Nov 20 '25 14:11

zhaoyou


requestScope.cookies will search for an request attribute named cookies. If you want to access the cookies property of the request, you need pageContext.request.cookies.

That said, accessing cookies is something you should do with Java code, inside a controller (servlet), and not in the view (JSP), which should only deal with HTML generation.

like image 28
JB Nizet Avatar answered Nov 20 '25 14:11

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!