Check if Cookie exists with JSP EL

前端 未结 4 937
-上瘾入骨i
-上瘾入骨i 2020-12-16 22:59

I am trying to check if a cookie exists on a JSP page using the Expression Language.

I have a cookie called persist which is set to either empty string

相关标签:
4条回答
  • 2020-12-16 22:59

    if using Tomcat 6+

    <c:if test="${ ! empty cookie['persist']}"> 
    Cookie doesn't exist
    </c:if>
    
    0 讨论(0)
  • 2020-12-16 23:06

    Closest what you can get is to check the cookie name in the request cookie header.

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

    However, when there's another cookie with name foopersist, it fails.

    If your container supports EL 2.2 (all Servlet 3.0 containers like Tomcat 7, Glassfish 3, etc do) then you could just use Map#containsKey().

    <c:if test="${cookie.containsKey('persist')}">
    

    If yours doesn't, best what you can do is to create an EL function (more concrete declaration example can be found somewhere near bottom of this answer):

    <c:if test="${util:mapContainsKey(cookie, 'persist')}">
    

    with

    public static boolean mapContainsKey(Map<String, Object> map, String key) {
        return map.containsKey(key);
    }
    
    0 讨论(0)
  • 2020-12-16 23:15

    use the cookie map to check that cookie exists or not ${cookie["persist"] == null}

    I hope it works

    0 讨论(0)
  • 2020-12-16 23:22

    If I understand correctly, you want to detect that it either doesn't exist or is empty.

    EDIT: ah. To verify that it doesn't exist, it must be null and not empty.

        <c:if test="${cookie.persist == null && cookie.persist != ''}">
       Cookie doesn't exist
        </c:if>
    
    0 讨论(0)
提交回复
热议问题