简体   繁体   English

如何使用EL表达式在JSP中设置cookie值?

[英]How to set a cookie value within JSP using an EL expression?

I'm trying to set a cookie value within a JSP without using Java code directly. 我正在尝试在JSP中设置cookie值而不直接使用Java代码。 I know I could do it by creating a custom tag lib for that, but I wanted to keep it simple so I'm trying to do that the same way I access cookies: with EL expressions. 我知道我可以通过为它创建一个自定义标记库来实现它,但我想保持简单,所以我试图像访问cookie一样:使用EL表达式。

I know I can read the value of a cookie using JSP EL with the expression ${cookie['cookieName'].value} , but how can I set a particular value to that cookie using EL? 我知道我可以使用带有表达式${cookie['cookieName'].value} JSP EL读取cookie的${cookie['cookieName'].value} ,但是如何使用EL为该cookie设置特定值? I found solutions using java code in the JSP, but I want to avoid that. 我在JSP中找到了使用java代码的解决方案,但我想避免这种情况。

So far I found ways to set variables using the c:set tag, but that doesn't accept expressions as the 'var' parameter so I can't do something like: 到目前为止,我找到了使用c:set标记设置变量的方法,但是它不接受表达式作为'var'参数,所以我做不了类似的事情:

<c:set var="${cookie['cookieName'].value}" value="123" />

I think the way to go is , but I don't know what expression to use for the var part of it, or how to write it so I can set the cookie value instead of just a variable. 我认为要走的路是,但我不知道用于var部分的表达式,或者如何编写它以便我可以设置cookie值而不仅仅是变量。

Any help is appreciated! 任何帮助表示赞赏!

There is no standard expression to set cookie in JSP. 在JSP中没有设置cookie的标准表达式。 You can use custom tag if you want OR use JSP script-less 如果您希望OR使用JSP无脚本,则可以使用自定义标记

<%

    javax.servlet.http.Cookie cookie 
           = new javax.servlet.http.Cookie("name", "value");

    // cookie.setXXX()

    response.addCookie(cookie);

%>

NOTE: Make sure cookie is added BEFORE the response is committed. 注意:确保在提交响应之前添加cookie。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM