@Override public void call(HttpServletRequest req, HttpServletResponse res) throws IOException { super.call(req, res); javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie("test", "test"); cookie.setDomain(".localhost"); cookie.setMaxAge(360); res.addCookie(cookie); cookie = new javax.servlet.http.Cookie("test2", "test2"); cookie.setDomain(".localhost"); res.addCookie(cookie); }
/** * @see ExternalContext#addResponseCookie(String, String, java.util.Map) * @param name * @param value * @param properties */ @Override public void addResponseCookie(String name, String value, Map<String, Object> properties) { HttpServletResponse res = (HttpServletResponse) response; Cookie cookie = new Cookie(name, value); if (properties != null && properties.size() != 0) { for (Map.Entry<String, Object> entry : properties.entrySet()) { String key = entry.getKey(); ALLOWABLE_COOKIE_PROPERTIES p = ALLOWABLE_COOKIE_PROPERTIES.valueOf(key); Object v = entry.getValue(); switch (p) { case domain: cookie.setDomain((String) v); break; case maxAge: cookie.setMaxAge((Integer) v); break; case path: cookie.setPath((String) v); break; case secure: cookie.setSecure((Boolean) v); break; default: throw new IllegalStateException(); // shouldn't happen } } } res.addCookie(cookie); }
/** * Sets a cookie according to request parameters * * @param request * @param response */ public void setCookie(HttpServletRequest request, HttpServletResponse response) { // Set obligatory cookie data final String cookieName = request.getParameter("name"); final String cookieValue = request.getParameter("value"); javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(cookieName, cookieValue); // Optional data is set only when given in request final String comment = request.getParameter("comment"); if (comment != null) { cookie.setComment(comment); } final String domain = request.getParameter("domain"); if (domain != null) { cookie.setDomain(domain); } final String maxAge = request.getParameter("max-age"); if (maxAge != null) { cookie.setMaxAge(Integer.parseInt(maxAge)); } final String path = request.getParameter("path"); if (path != null) { cookie.setPath(path); } final String secure = request.getParameter("secure"); if (secure != null) { cookie.setSecure(Boolean.parseBoolean(secure)); } final String version = request.getParameter("cookie-version"); if (version != null) { cookie.setVersion(Integer.parseInt(version)); } response.addCookie(cookie); }
/** * 设置cookie * * @param response * @param key = asuraSessionId * @param value = sessionId */ public void saveCookie(final HttpServletResponse response, final String key, final String value) { final Cookie cookie = new Cookie(key, value); cookie.setDomain(DOMAIN); cookie.setMaxAge(604800); cookie.setPath("/"); response.addCookie(cookie); }
/* * (non-Javadoc) * * @see * com.newtouch.lion.dsession.store.DistributedCookieStore#invalidate(com * .newtouch.lion.session.context.RequestContext) */ @Override public void invalidate(DistributedSessionContext sessionContext) { Cookie[] cookies = sessionContext.getRequest().getCookies(); // 判断是否为空 if (cookies == null || cookies.length == 0) { return; } for (Cookie cookie : cookies) { String cookieName = cookie.getName(); String decodeCookieName = cookieName; // 编码 if (distributedCookieAttributeConfig.getEncoder() != null) { decodeCookieName = distributedCookieAttributeConfig.getEncoder().encodeName(decodeCookieName); } if (distributedCookieAttributeConfig.isMatch(decodeCookieName)) { cookie.setDomain(distributedCookieAttributeConfig.getDomain()); cookie.setPath(distributedCookieAttributeConfig.getPath()); cookie.setSecure(distributedCookieAttributeConfig.isSecure()); cookie.setMaxAge(0); sessionContext.getResponse().addCookie(cookie); } } }
protected Cookie toServletCookie(org.apache.commons.httpclient.Cookie commonsCookie) { Cookie cookie = new Cookie(commonsCookie.getName(), commonsCookie.getValue()); String domain = commonsCookie.getDomain(); if (Validator.isNotNull(domain)) { cookie.setDomain(domain); } Date expiryDate = commonsCookie.getExpiryDate(); if (expiryDate != null) { int maxAge = (int) (expiryDate.getTime() - System.currentTimeMillis()); maxAge = maxAge / 1000; if (maxAge > -1) { cookie.setMaxAge(maxAge); } } String path = commonsCookie.getPath(); if (Validator.isNotNull(path)) { cookie.setPath(path); } cookie.setSecure(commonsCookie.getSecure()); cookie.setVersion(commonsCookie.getVersion()); return cookie; }
public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (SystemConfigs.get("memSessionSwitch", "true").equalsIgnoreCase("true")) { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; String sid = request.getSession().getId(); if (StringUtils.isNotBlank(request.getParameter("jsessionid"))) { String jsessionid = request.getParameter("jsessionid"); if (!StringUtils.equals(sid, jsessionid)) { HttpSession session = request.getSession(false); if (session != null) session.invalidate(); Cookie cookie = new Cookie("JSESSIONID", jsessionid); cookie.setDomain(request.getServerName()); cookie.setPath("/"); response.addCookie(cookie); sid = jsessionid; } } sessionLog.info("get session in memcached..."); filterChain.doFilter(new HttpServletRequestWrapper(sid, request), servletResponse); } else { sessionLog.info("get session in httpsession..."); filterChain.doFilter(servletRequest, servletResponse); } }
/* ------------------------------------------------------------ */ protected void onResponseHeader(Buffer name, Buffer value) throws IOException { super.onResponseHeader(name, value); if (HttpHeaders.CACHE.getOrdinal(name) == HttpHeaders.SET_COOKIE_ORDINAL) { String cname = null; String cvalue = null; QuotedStringTokenizer tok = new QuotedStringTokenizer(value.toString(), "=;", false, false); tok.setSingle(false); if (tok.hasMoreElements()) cname = tok.nextToken(); if (tok.hasMoreElements()) cvalue = tok.nextToken(); Cookie cookie = new Cookie(cname, cvalue); while (tok.hasMoreTokens()) { String token = tok.nextToken(); if ("Version".equalsIgnoreCase(token)) cookie.setVersion(Integer.parseInt(tok.nextToken())); else if ("Comment".equalsIgnoreCase(token)) cookie.setComment(tok.nextToken()); else if ("Path".equalsIgnoreCase(token)) cookie.setPath(tok.nextToken()); else if ("Domain".equalsIgnoreCase(token)) cookie.setDomain(tok.nextToken()); else if ("Expires".equalsIgnoreCase(token)) { tok.nextToken(); // TODO } else if ("Max-Age".equalsIgnoreCase(token)) { tok.nextToken(); // TODO } else if ("Secure".equalsIgnoreCase(token)) cookie.setSecure(true); } BayeuxClient.this.setCookie(cookie); } }
/** * 添加cookie * * @param request HttpServletRequest * @param response HttpServletResponse * @param name cookie名称 * @param value cookie�? * @param maxAge 有效�?单位: �? * @param path 路径 * @param domain �? * @param secure 是否启用加密 */ public static void addCookie( HttpServletRequest request, HttpServletResponse response, String name, String value, Integer maxAge, String path, String domain, Boolean secure) { Assert.notNull(request); Assert.notNull(response); Assert.hasText(name); try { name = URLEncoder.encode(name, "UTF-8"); value = URLEncoder.encode(value, "UTF-8"); Cookie cookie = new Cookie(name, value); if (maxAge != null) { cookie.setMaxAge(maxAge); } if (StringUtils.isNotEmpty(path)) { cookie.setPath(path); } if (StringUtils.isNotEmpty(domain)) { cookie.setDomain(domain); } if (secure != null) { cookie.setSecure(secure); } response.addCookie(cookie); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }
public void set(String name, String value, String domain, String path, int seconds) { LOGGER.debug("name=" + name + ",value=" + value + ",seconds=" + seconds); Cookie c = new Cookie(name, value); if (!StringUtil.isNullOrEmpty(domain)) c.setDomain(domain); else c.setDomain(DEFAULT_DOMAIN); if (!StringUtil.isNullOrEmpty(path)) c.setPath(path); else c.setPath(DEFAULT_PATH); // cookies.setMaxAge(-1);//设置cookie经过多长秒后被删除。如果0,就说明立即删除。如果是负数就表明当浏览器关闭时自动删除。 c.setMaxAge(seconds); response.addCookie(c); }
/** * Set Cookie to response. * * @param name cookie name * @param value cookie value * @param maxAgeInSeconds -1: clear cookie when close browser. 0: clear cookie immediately. n>0 : * max age in n seconds. * @param path see Cookie.setPath(String) * @param domain the domain name within which this cookie is visible; form is according to RFC * 2109 */ public Controller setCookie( String name, String value, int maxAgeInSeconds, String path, String domain) { Cookie cookie = new Cookie(name, value); if (domain != null) cookie.setDomain(domain); cookie.setMaxAge(maxAgeInSeconds); cookie.setPath(path); response.addCookie(cookie); return this; }
public boolean delete(String n, String domain, String path) { if (!StringUtil.isNullOrEmpty(n)) { Cookie c = get(n); if (c != null) { c.setMaxAge(0); // 如果0,就说明立即删除 if (!StringUtil.isNullOrEmpty(domain)) c.setDomain(domain); else c.setDomain(DEFAULT_DOMAIN); if (!StringUtil.isNullOrEmpty(path)) c.setPath(path); // 不要漏掉 else c.setPath(DEFAULT_PATH); response.addCookie(c); return true; } } return false; }
public static void removeCookie(HttpServletResponse response, Cookie cookie, String domain) { if (cookie != null) { cookie.setPath("/"); cookie.setValue(""); cookie.setMaxAge(0); cookie.setDomain(domain); response.addCookie(cookie); } }
/** * Set a persisten cookie on the client that will expire after a maximum age (given in seconds). */ public void setCookie(String name, String value, int seconds_age) { Cookie cookie = new Cookie(name, value); // 设置cookie作用时间、domain和path。 cookie.setMaxAge(seconds_age); cookie.setDomain(getCookieDomain()); cookie.setPath(getCookiePath()); webContext.getResponse().addCookie(cookie); }
@Test public void testInvalidDomain() throws MalformedURLException { CookieJar jar = new CookieJar(); Cookie cookie = new Cookie("myname", "myvalue"); cookie.setDomain(".10gen.com"); cookie.setPath("/subdir"); jar.addCookie(new URL("http://othersite.com/"), cookie); assertSame(0, jar.getAll().size()); }
protected void configureSessionCookie(Cookie cookie) { super.configureSessionCookie(cookie); String host = getServerName(); String domain = _getDomain(host); if (domain != null) { cookie.setDomain(domain); } }
/** * Setup a cookie: expiration date, path, domain + send it to the response. * * @param cookie The cookie to setup. * @param sessionCookie Whether the cookie is only for this session, or for a longer period. * @param cookieDomain The domain for which the cookie is set. * @param response The servlet response. */ public void setupCookie( Cookie cookie, boolean sessionCookie, String cookieDomain, HttpServletResponse response) { if (!sessionCookie) { setMaxAge(cookie); } cookie.setPath(this.cookiePath); if (cookieDomain != null) { cookie.setDomain(cookieDomain); } addCookie(response, cookie); }
/** * 取消cookie * * @param request * @param response * @param name * @param domain */ public static void cancleCookie( HttpServletRequest request, HttpServletResponse response, String name, String domain) { Cookie cookie = new Cookie(name, ""); cookie.setMaxAge(0); String ctx = request.getContextPath(); cookie.setPath(StringUtils.isBlank(ctx) ? "/" : ctx); if (StringUtils.isNotBlank(domain)) { cookie.setDomain(domain); } response.addCookie(cookie); }
/** * 把用户名写入cookie * * @param userName userName * @param response response * @throws UnsupportedEncodingException UnsupportedEncodingException */ private void writeCookieWithName(final String userName, final HttpServletResponse response) throws UnsupportedEncodingException { // "UN"的Cookie记录着用户登录后的用户名信息(只会在session中存在) Cookie cookie = new Cookie("UN", null); cookie.setDomain(DomainConstant.DOMAIN); cookie.setMaxAge( StringUtils.isNotEmpty(keepLogin) ? Integer.parseInt(app.getInitParameter("UNCookieTimeOut")) : -1); cookie.setPath("/"); cookie.setValue(URLEncoder.encode(userName, "UTF-8")); response.addCookie(cookie); // "unUserName"保存了用户的登录名,不论用户是否登录状态都会保留 cookie = new Cookie("unUserName", null); cookie.setDomain(DomainConstant.DOMAIN); cookie.setMaxAge(Integer.parseInt(app.getInitParameter("userNameCookieTimeOut"))); cookie.setPath("/"); String unUserName = userName; String userId = userName; if (unUserName.indexOf("^!^") != -1) { unUserName = unUserName.substring(0, unUserName.indexOf("^!^")); userId = userName.substring(userName.indexOf("^!^") + ID_POS, userName.length()); } cookie.setValue(URLEncoder.encode(unUserName, "UTF-8")); response.addCookie(cookie); // 临时保持原样LSTA cookie给攻略用。 // LvmamaMd5Key这个类是原来老LVMAMA COMMON里的类,我在新LVMAMA COMMON里没找到,也不敢移进去 // 暂时保留在PET SSO项目里,到时采用新方法后一起移除 // TODO BY liuyi cookie = new Cookie("LSTA", null); cookie.setDomain(DomainConstant.DOMAIN); cookie.setMaxAge( StringUtils.isNotEmpty(keepLogin) ? Integer.parseInt(app.getInitParameter("UNCookieTimeOut")) : -1); cookie.setPath("/"); cookie.setValue(LvmamaMd5Key.encode(userId)); response.addCookie(cookie); }
@Override public void addResponseCookie(final Cookie cookie) { javax.servlet.http.Cookie c = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue()); c.setSecure(cookie.isSecure()); c.setPath(cookie.getPath()); c.setMaxAge(cookie.getMaxAge()); c.setHttpOnly(cookie.isHttpOnly()); c.setComment(cookie.getComment()); c.setDomain(cookie.getDomain()); this.response.addCookie(c); }
@Override public String execute() throws Exception { String tgc = getRequest().getParameter(CookieUtil.COOKIE_TGC); String u = getRequest().getParameter(CookieUtil.COOKIE_U); if (tgc != null && !"".equals(tgc.trim())) { Cookie tgcCookie = new Cookie(CookieUtil.COOKIE_TGC, tgc); tgcCookie.setDomain(CookieUtil.DEFAULT_DOMAIN); tgcCookie.setMaxAge(60 * 60 * 24 * 182); tgcCookie.setPath("/"); getResponse().addCookie(tgcCookie); } if (u != null && !"".equals(u.trim())) { Cookie uCookie = new Cookie("U", u); uCookie.setDomain(CookieUtil.DEFAULT_DOMAIN); uCookie.setMaxAge(60 * 60 * 24 * 183); uCookie.setPath("/"); getResponse().addCookie(uCookie); } getResponse().sendRedirect(getRedirectUrl()); return null; }
public void setValue(Object key, Object value) { if (this.response == null) { throw new UnsupportedOperationException(); } if (key == null) { throw new NullPointerException("Key can't be null."); } if (this.cookieMap == null) { this.initCookie(); } String name = key.toString(); Cookie cookie = null; if (value == null) { Cookie oldCookie = (Cookie) this.cookieMap.get(name); if (oldCookie != null) { cookie = new Cookie(this.encodeStr(name), ""); cookie.setMaxAge(0); cookie.setDomain(oldCookie.getDomain()); cookie.setPath(oldCookie.getPath()); } } else if (value instanceof Cookie) { cookie = (Cookie) value; String cookieName = this.decodeStr(cookie.getName(), this.response.getCharacterEncoding()); if (!(name.equals(cookieName))) { throw new IllegalArgumentException( "The cookie name not same, name:[" + name + "], cookie:[" + cookieName + "]"); } } else { String str = value.toString(); if (this.compressValue) { BooleanRef ziped = new BooleanRef(); str = this.doDeflater(str, ziped); if (ziped.value) { str = COMPRESS_VALUE_PREFIX.concat(str); } else { str = this.encodeStr(str); } } else { str = this.encodeStr(str); } cookie = new Cookie(this.encodeStr(name), str); cookie.setPath(this.request.getContextPath().concat("/")); } if (cookie != null) { this.response.addCookie(cookie); if (cookie.getMaxAge() == 0) { this.cookieMap.remove(name); } else { this.cookieMap.put(name, cookie); } } }
@Test public void testClean() throws MalformedURLException, InterruptedException { CookieJar jar = new CookieJar(); // Normal cookie Cookie normalCookie = new Cookie("normal", "mynorm"); normalCookie.setDomain(".10gen.com"); normalCookie.setPath("/"); normalCookie.setMaxAge(9999); jar.addCookie(new URL("http://www.10gen.com/"), normalCookie); // Expired Cookie Cookie expiredCookie = new Cookie("expired", "myvalue"); expiredCookie.setDomain(".10gen.com"); expiredCookie.setPath("/"); expiredCookie.setMaxAge(1); jar.addCookie(new URL("http://www.10gen.com/"), expiredCookie); // Nonpersistent cookie Cookie nonpresistCookie = new Cookie("nonpersist", "myval2"); nonpresistCookie.setDomain(".10gen.com"); nonpresistCookie.setPath("/"); jar.addCookie(new URL("http://www.10gen.com/"), nonpresistCookie); assertEquals(3, jar.getAll().size()); Thread.sleep(2000); List<Cookie> removedCookies = jar.clean(false); assertEquals(1, removedCookies.size()); assertEquals("expired", removedCookies.get(0).getName()); removedCookies = jar.clean(true); assertEquals(1, removedCookies.size()); assertEquals("nonpersist", removedCookies.get(0).getName()); }
/** * 设置COOKIE 〈功能详细描述〉 * * @param request * @param response * @param cookieName - 名称 String * @param cookieValue - 值 String * @param cookieTime -int 时间 -1表示关闭浏览器即失效 */ public static void setCookie( HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieTime) { Cookie cookie = new Cookie(cookieName, cookieValue); String host = request.getServerName(); cookie.setPath("/"); cookie.setDomain(host); cookie.setMaxAge(cookieTime); response.addCookie(cookie); }
@Test public void testSecure() throws MalformedURLException { CookieJar jar = new CookieJar(); Cookie cookie = new Cookie("myname", "myvalue"); cookie.setDomain(".10gen.com"); cookie.setPath("/"); cookie.setSecure(true); jar.addCookie(new URL("https://www.10gen.com"), cookie); assertSame(cookie, jar.getActiveCookies(new URL("https://10gen.com/")).get("myname")); assertSame(0, jar.getActiveCookies(new URL("http://10gen.com/")).size()); }
@Test public void setCookieTest() throws IOException, ServletException, ExecutionException, InterruptedException { final AtomicReference<Cookie> cValue = new AtomicReference<Cookie>(); final AtomicReference<AtmosphereResource> r = new AtomicReference<AtmosphereResource>(); framework.addAtmosphereHandler( "/*", new AtmosphereHandler() { @Override public void onRequest(AtmosphereResource resource) throws IOException { resource.getResponse().addCookie(resource.getRequest().getCookies()[0]); r.set(resource); resource.getBroadcaster().addAtmosphereResource(resource); } @Override public void onStateChange(AtmosphereResourceEvent event) throws IOException { Cookie[] c = event.getResource().getRequest().getCookies(); cValue.set(c[0]); } @Override public void destroy() {} }); Set<Cookie> c = new HashSet<Cookie>(); Cookie a = new Cookie("yo", "man"); a.setComment("kdaskjdaskda"); a.setDomain("dasdasdasd"); a.setHttpOnly(true); a.setPath("/ya"); c.add(a); AtmosphereRequest request = new AtmosphereRequestImpl.Builder().cookies(c).pathInfo("/a").build(); AtmosphereResponse response = AtmosphereResponseImpl.newInstance().delegateToNativeResponse(false); response.destroyable(false); framework.doCometSupport(request, response); r.get().getBroadcaster().broadcast("yo").get(); assertNotNull(cValue.get()); Cookie i = c.iterator().next(); assertEquals(i.getName(), cValue.get().getName()); assertEquals(i.getValue(), cValue.get().getValue()); assertEquals( "yo=man; Domain=dasdasdasd; Path=/ya; HttpOnly", response.headers().get("Set-Cookie")); }
@Test public void testClientSideCookieDefaultPath() { cookieGenerator.setCookieName(JSESSIONID); cookieGenerator.setHttpOnly(false); // client side cookieGenerator.addCookie(response, "cookie_monster"); final Cookie expectedCookie = new Cookie(JSESSIONID, "cookie_monster"); expectedCookie.setPath("/"); expectedCookie.setSecure(false); expectedCookie.setMaxAge(NEVER_EXPIRES); expectedCookie.setDomain("what a domain"); Mockito.verify(response).addCookie(Mockito.argThat(new CookieArgumentMatcher(expectedCookie))); assertNoHeaderAdjustments(); }
@Test public void testPath() throws MalformedURLException { CookieJar jar = new CookieJar(); Cookie cookie = new Cookie("myname", "myvalue"); cookie.setDomain(".10gen.com"); cookie.setPath("/subdir"); jar.addCookie(new URL("http://www.10gen.com/subdir"), cookie); assertSame( cookie, jar.getActiveCookies(new URL("http://10gen.com/subdir/moo/baa.html")).get("myname")); assertSame(0, jar.getActiveCookies(new URL("http://10gen.com/otherdir/")).size()); }
/** * Remove a cookie. * * @param request The servlet request. * @param response The servlet response. * @param cookieName The name of the cookie that must be removed. */ private void removeCookie( HttpServletRequest request, HttpServletResponse response, String cookieName) { Cookie cookie = getCookie(request.getCookies(), cookieName); if (cookie != null) { cookie.setMaxAge(0); cookie.setPath(this.cookiePath); addCookie(response, cookie); String cookieDomain = getCookieDomain(request); if (cookieDomain != null) { cookie.setDomain(cookieDomain); addCookie(response, cookie); } } }
private static Cookie createCookie( String cookieName, String value, String domain, String path, HttpServletRequest httpRequest) { Cookie cookie = new Cookie(cookieName, value); if (domain != null) { cookie.setDomain(domain); } if (path != null) { cookie.setPath(path); } else { // default to the context path, otherwise you get /security and such in some places cookie.setPath(getWebappContext(httpRequest)); } return cookie; }