Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

java - Check if Cookie exists with JSP EL

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 or "checked".

If would like to check if the persist cookie exists.

I have tried the following:

<c:if test="${cookie.persist == null}">

<c:if test="${empty cookie.persist}">

Both of the above statements are true when the value of the persist cookie is the empty string and false when the value of the cookie is checked.

How do I distinguish between a cookie with the empty string as its value, and a cookie that does not exist.

(Note: I can easily work around this problem by assigning a non empty value to the cookie instead of the empty string.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...