java - Creating a cookie inside a jax-rs endpoint -
i have jax-rs endpoint. purpose of endpoint authorize user. need login details inside cookie. below have mentioned related part of code.
public response authorize(@context httpservletrequest request) throws urisyntaxexception { if (authnresult.isauthenticated()) { //todo create cookie maintain login state cookie authcookie = new cookie(frameworkconstants.commonauth_cookie, "test"); authcookie.setsecure(true); authcookie.sethttponly(false); authcookie.setmaxage(5 * 60); }
edit:
this first time when creating cookies. followed tutorials. in these tutorials has added created cookie response. inside endpoint can't access response. how can create cookie? please advice me.
updated code:
public response authorize(@context httpservletrequest request) throws urisyntaxexception { newcookie cookie = new newcookie("cookiename","cookievalue"); response.responsebuilder builder = response.ok("cool stuff"); builder.cookie(cookie); response response=builder.build(); cookie[] cookies = request.getcookies(); }
what need know how access newly created cookie.
you can create javax.ws.rs.core.newcookie
. there bunch of different constructors, go through api docs.
then can add cookies through responsebuilder#cookie(newcookie)
. example:
@get public response getcookie() { newcookie cookie = new newcookie("name", "value", "path", "domain", "comment", 300, true, true); responsebuilder builder = response.ok("cool stuff"); builder.cookie(cookie); return builder.build(); }
update (with complete example)
@path("cookie") public class cookieresource { @get public response getcookie(@cookieparam("a-cookie") string cookie) { response response = null; if (cookie == null) { response = response.ok("a-cookie: cookie #1") .cookie(new newcookie("a-cookie", "cookie #1")) .build(); return response; } else { string cookienum = cookie.substring(cookie.indexof("#") + 1); int number = integer.parseint(cookienum); number++; string updatedcookie = "cookie #" + number; response = response.ok("a-cookie: " + updatedcookie) .cookie(new newcookie("a-cookie", updatedcookie)) .build(); return response; } } }
after 38 requests, can see result. used firefox plugin firebug. can see sent cookie #37, , returned cookie #38
if need trying access cookie client (as suggested in comment), may suitable question on so. maybe off topic discussion, rely on technology. if not looking for, maybe better explanation of trying accomplish help.
Comments
Post a Comment