Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

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? I found solutions using java code in the JSP, but I want to avoid that.

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="${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.

Any help is appreciated!

like image 241
Edy Bourne Avatar asked Mar 21 '23 02:03

Edy Bourne


1 Answers

There is no standard expression to set cookie in JSP. You can use custom tag if you want OR use JSP script-less

<%

    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.

like image 129
Loc Avatar answered Apr 06 '23 03:04

Loc