使用JSP EL检查Cookie是否存在
我正在尝试使用表达式语言检查 JSP 页面上是否存在 cookie。
我有一个名为 persist
的 cookie,它设置为空字符串或“已检查”。
如果想检查 persist
cookie 是否存在。
我尝试过以下操作:
当 persist
cookie 的值为空字符串时,上述两条语句为 true
;当 cookie 的值为 代码>已检查。
如何区分值为空字符串的 cookie 和不存在的 cookie。
(注意:我可以通过为 cookie 分配一个非空值而不是空字符串来轻松解决这个问题。)
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.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您能得到的最接近的信息是检查请求
cookie
标头中的 cookie 名称。但是,当存在另一个名为
foopersist
的 cookie 时,它会失败。如果您的容器支持 EL 2.2(所有 Servlet 3.0 容器,如 Tomcat 7、Glassfish 3 等),那么您只需使用 Map#containsKey() 即可。
如果你没有,你能做的最好的事情就是创建一个 EL 函数(更具体的声明示例可以在 这个答案):
of-jsp-servlet/2525995# 2525995
Closest what you can get is to check the cookie name in the request
cookie
header.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()
.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):
with
使用cookie映射来检查cookie是否存在
${cookie["persist"] == null}
我希望它能起作用
use the cookie map to check that cookie exists or not
${cookie["persist"] == null}
I hope it works
如果我理解正确的话,您想要检测它不存在或为空。
编辑:啊。要验证它不存在,它必须为 null 并且不为空。
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.
如果使用 Tomcat 6+
if using Tomcat 6+