检查JSP是否存在Cookie [英] Check if Cookie exists with JSP EL
问题描述
我正在尝试使用表达式语言检查JSP页面上是否存在cookie。
I am trying to check if a cookie exists on a JSP page using the Expression Language.
我有一个名为的cookie
设置为空字符串或已选中。
I have a cookie called persist
which is set to either empty string or "checked".
如果想检查是否持续
cookie存在。
If would like to check if the persist
cookie exists.
我尝试了以下内容:
< c:if test =$ {cookie.persist == null}>
< c: if test =$ {empty cookie.persist}>
上述两个陈述都是 true
当 persist
cookie的值为空字符串时,如果cookie的值为,则为false
。
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
.
如何区分以空字符串作为其值的cookie和不存在的cookie。
How do I distinguish between a cookie with the empty string as its value, and a cookie that does not exist.
(注意:我可以通过为cookie而不是空字符串分配非空值来轻松解决此问题。)
(Note: I can easily work around this problem by assigning a non empty value to the cookie instead of the empty string.)
推荐答案
最接近的是检查请求 cookie
标题中的cookie名称。
Closest what you can get is to check the cookie name in the request cookie
header.
<c:if test="${fn:contains(header.cookie, 'persist=')}">
但是,当有另一个名为的cookie时,foopersist
,它失败了。
However, when there's another cookie with name foopersist
, it fails.
如果您的容器支持EL 2.2(所有Servlet 3.0容器,如Tomcat 7,Glassfish 3等),那么您可以使用 Map#containsKey ()
。
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')}">
如果你没有,最好的办法是创建一个EL函数(更具体的声明)示例可以在此答案底部附近找到:)
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);
}
这篇关于检查JSP是否存在Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!