Java Code Examples for javax.servlet.http.Cookie

The following are top voted examples for showing how to use javax.servlet.http.Cookie. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: tomcat7   File: ImplicitObjectELResolver.java   View source code 9 votes vote down vote up
public Map<String,Cookie> getCookie() {
    if (this.cookie == null) {
        this.cookie = new ScopeMap<Cookie>() {
            @Override
            protected Enumeration<String> getAttributeNames() {
                Cookie[] c = ((HttpServletRequest) page.getRequest())
                        .getCookies();
                if (c != null) {
                    Vector<String> v = new Vector<String>();
                    for (int i = 0; i < c.length; i++) {
                        v.add(c[i].getName());
                    }
                    return v.elements();
                }
                return null;
            }

            @Override
            protected Cookie getAttribute(String name) {
                Cookie[] c = ((HttpServletRequest) page.getRequest())
                        .getCookies();
                if (c != null) {
                    for (int i = 0; i < c.length; i++) {
                        if (name.equals(c[i].getName())) {
                            return c[i];
                        }
                    }
                }
                return null;
            }

        };
    }
    return this.cookie;
}
 
Example 2
Project: buenojo   File: CsrfCookieGeneratorFilter.java   View source code 9 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    // Spring put the CSRF token in session attribute "_csrf"
    CsrfToken csrfToken = (CsrfToken) request.getAttribute("_csrf");

    // Send the cookie only if the token has changed
    String actualToken = request.getHeader("X-CSRF-TOKEN");
    if (actualToken == null || !actualToken.equals(csrfToken.getToken())) {
        // Session cookie that will be used by AngularJS
        String pCookieName = "CSRF-TOKEN";
        Cookie cookie = new Cookie(pCookieName, csrfToken.getToken());
        cookie.setMaxAge(-1);
        cookie.setHttpOnly(false);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
    filterChain.doFilter(request, response);
}
 
Example 3
Project: shoucang   File: CsrfCookieGeneratorFilter.java   View source code 8 votes vote down vote up
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    // Spring put the CSRF token in session attribute "_csrf"
    CsrfToken csrfToken = (CsrfToken) request.getAttribute("_csrf");

    // Send the cookie only if the token has changed
    String actualToken = request.getHeader("X-CSRF-TOKEN");
    if (actualToken == null || !actualToken.equals(csrfToken.getToken())) {
        // Session cookie that will be used by AngularJS
        String pCookieName = "CSRF-TOKEN";
        Cookie cookie = new Cookie(pCookieName, csrfToken.getToken());
        cookie.setMaxAge(-1);
        cookie.setHttpOnly(false);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
    filterChain.doFilter(request, response);
}
 
Example 4
Project: netty-socketio-demo   File: CookieUtils.java   View source code 7 votes vote down vote up
public static void deleteCookie(HttpServletRequest request, HttpServletResponse response,
        Cookie cookie, String domain, String path) {
    if (cookie != null) {
        if(StringUtils.isNotBlank(domain)){
            cookie.setDomain(domain);
        }
        cookie.setPath(path);
        cookie.setValue("");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }
}
 
Example 5
Project: garlicts   File: WebUtil.java   View source code 6 votes vote down vote up
/**
 * 从 Cookie 中获取数据
 */
public static String getCookie(HttpServletRequest request, String name) {
    String value = "";
    try {
        Cookie[] cookieArray = request.getCookies();
        if (cookieArray != null) {
            for (Cookie cookie : cookieArray) {
                if (StringUtil.isNotEmpty(name) && name.equals(cookie.getName())) {
                    value = CodecUtil.decodeURL(cookie.getValue());
                    break;
                }
            }
        }
    } catch (Exception e) {
        logger.error("获取 Cookie 出错!");
        throw new RuntimeException(e);
    }
    return value;
}
 
Example 6
Project: dooo   File: UserAuth.java   View source code 6 votes vote down vote up
private static String getGidCookie(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        Cookie[] var2 = cookies;
        int var3 = cookies.length;

        for (int var4 = 0; var4 < var3; ++var4) {
            Cookie cookie = var2[var4];
            if (WXZID_COOKIE_NAME.equals(cookie.getName()) && cookie.getValue() != null) {
                try {
                    return UrlUtils.decode(cookie.getValue());
                } catch (Exception var7) {
                    LOGGER.error("wxzid [" + cookie.getValue() + "] deserialize failed,", var7);
                    return null;
                }
            }
        }
    }
    return null;
}
 
Example 7
Project: angular-spring-starter   File: TokenHelper.java   View source code 6 votes vote down vote up
public String getToken( HttpServletRequest request ) {
    /**
     *  Getting the token from Cookie store
     */
    Cookie authCookie = getCookieValueByName( request, AUTH_COOKIE );
    if ( authCookie != null ) {
        return authCookie.getValue();
    }
    /**
     *  Getting the token from Authentication header
     *  e.g Bearer your_token
     */
    String authHeader = request.getHeader(AUTH_HEADER);
    if ( authHeader != null && authHeader.startsWith("Bearer ")) {
        return authHeader.substring(7);
    }

    return null;
}
 
Example 8
Project: myfaces-trinidad   File: ServletCookieMap.java   View source code 6 votes vote down vote up
@Override
public boolean containsKey(final Object key)
{
  final Cookie[] cookies = _httpServletRequest.getCookies();
  if (cookies == null)
  {
    return false;
  }
  for (Cookie element : cookies)
  {
    if (element.getName().equals(key))
    {
      return true;
    }
  }

  return false;
}
 
Example 9
Project: incubator-servicecomb-java-chassis   File: TestCookieProcessor.java   View source code 6 votes vote down vote up
@Test
public void testGetValueCookiesDate() throws Exception {
  Date date = new Date();
  String strDate = ISO8601Utils.format(date);
  Cookie[] cookies = new Cookie[] {new Cookie("c1", strDate)};
  new Expectations() {
    {
      request.getCookies();
      result = cookies;
    }
  };

  CookieProcessor processor = createProcessor("c1", Date.class);
  Object value = processor.getValue(request);
  Assert.assertEquals(strDate, ISO8601Utils.format((Date) value));
}
 
Example 10
Project: apache-tomcat-7.0.73-with-comment   File: RequestFacade.java   View source code 6 votes vote down vote up
@Override
public Cookie[] getCookies() {

    if (request == null) {
        throw new IllegalStateException(
                        sm.getString("requestFacade.nullRequest"));
    }

    Cookie[] ret = null;

    /*
     * Clone the returned array only if there is a security manager
     * in place, so that performance won't suffer in the non-secure case
     */
    if (SecurityUtil.isPackageProtectionEnabled()){
        ret = AccessController.doPrivileged(
            new GetCookiesPrivilegedAction());
        if (ret != null) {
            ret = ret.clone();
        }
    } else {
        ret = request.getCookies();
    }

    return ret;
}
 
Example 11
Project: http-agent   File: AgentServlet.java   View source code 6 votes vote down vote up
/**
 * Copy cookie from the proxy to the servlet client. Replaces cookie path to local path and renames cookie to avoid
 * collisions.
 */
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Header header) {
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    String path = servletRequest.getContextPath(); // path starts with / or is empty string
    path += servletRequest.getServletPath(); // servlet path starts with / or is empty string

    for (HttpCookie cookie : cookies) {
        // set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = getCookieNamePrefix() + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); // set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}
 
Example 12
Project: parabuild-ci   File: BuildsStatusesPage.java   View source code 6 votes vote down vote up
/**
   */
  private int getRememberedDisplayGroupID(final HttpServletRequest request) {
    // try to get the display group from session
    final Integer displayGroupID = (Integer) request.getSession().getAttribute(WebUIConstants.SESSION_ATTR_SELECTED_DISPLAY_GROUP_ID);
    if (displayGroupID != null) {
      return displayGroupID.intValue();
    }

    // try to get the display group from the cookie
    final Cookie[] cookies = request.getCookies();
    if (cookies != null) {
      for (int i = 0; i < cookies.length; i++) {
        final Cookie c = cookies[i];
//        if (log.isDebugEnabled()) log.debug("c.getName(): " + c.getName());
//        if (log.isDebugEnabled()) log.debug("c.getValue(): " + c.getValue());
        if (c.getName().equals(WebUIConstants.COOKIE_DISPLAY_GROUP_ID)) {
          if (StringUtils.isValidInteger(c.getValue())) {
            return getValidDisplayGroupID(Integer.parseInt(c.getValue()));
          } else {
            return DisplayGroup.DISPLAY_GROUP_ID_ALL;
          }
        }
      }
    }

    if (displayGroupID != null) {
      return getValidDisplayGroupID(displayGroupID.intValue());
    }
    return DisplayGroup.DISPLAY_GROUP_ID_ALL;
  }
 
Example 13
Project: springboot-shiro-cas-mybatis   File: SendTicketGrantingTicketActionTests.java   View source code 6 votes vote down vote up
@Test
public void verifyTgtToSetRemovingOldTgt() throws Exception {
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final MockHttpServletRequest request = new MockHttpServletRequest();

    final TicketGrantingTicket tgt = mock(TicketGrantingTicket.class);
    when(tgt.getId()).thenReturn("test");

    request.setCookies(new Cookie("TGT", "test5"));
    WebUtils.putTicketGrantingTicketInScopes(this.context, tgt);
    this.context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, response));

    assertEquals("success", this.action.execute(this.context).getId());
    request.setCookies(response.getCookies());
    assertEquals(tgt.getId(), this.ticketGrantingTicketCookieGenerator.retrieveCookieValue(request));
}
 
Example 14
Project: tomcat7   File: Response.java   View source code 6 votes vote down vote up
/**
 * Add the specified Cookie to those that will be included with
 * this Response.
 *
 * @param cookie Cookie to be added
 */
@Override
public void addCookie(final Cookie cookie) {

    // Ignore any call from an included servlet
    if (included || isCommitted()) {
        return;
    }

    final StringBuffer sb = generateCookieString(cookie);
    //if we reached here, no exception, cookie is valid
    // the header name is Set-Cookie for both "old" and v.1 ( RFC2109 )
    // RFC2965 is not supported by browsers and the Servlet spec
    // asks for 2109.
    addHeader("Set-Cookie", sb.toString());
}
 
Example 15
Project: airsonic   File: PlayerService.java   View source code 6 votes vote down vote up
/**
 * Reads the player ID from the cookie in the HTTP request.
 *
 * @param request  The HTTP request.
 * @param username The name of the current user.
 * @return The player ID embedded in the cookie, or <code>null</code> if cookie is not present.
 */
private String getPlayerIdFromCookie(HttpServletRequest request, String username) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null) {
        return null;
    }
    String cookieName = COOKIE_NAME + "-" + StringUtil.utf8HexEncode(username);
    for (Cookie cookie : cookies) {
        if (cookieName.equals(cookie.getName())) {
            return StringUtils.trimToNull(cookie.getValue());
        }
    }
    return null;
}
 
Example 16
Project: sdudoc   File: CookieUtil.java   View source code 6 votes vote down vote up
/**添加cookie*/
public List<Cookie> addCookie(User user) {
	Cookie cookieU = new Cookie(Constants.COOKIE_USERNAME, user.getUsername());
	Cookie cookieP = new Cookie(Constants.COOKIE_PASSWORD, user.getPassword());
	cookieU.setMaxAge(60 * 60 * 24 * 14);
	cookieP.setMaxAge(60 * 60 * 24 * 14);
	cookieU.setPath("/");
	cookieP.setPath("/");
	List<Cookie> list = new ArrayList<Cookie>();
	list.add(cookieP);
	list.add(cookieU);
	return list;
}
 
Example 17
Project: stage-job   File: CookieUtil.java   View source code 6 votes vote down vote up
/**
 * 保存
 * @param response
 * @param key
 * @param value
 * @param ifRemember 
 */
public static void set(HttpServletResponse response, String key, String value, boolean ifRemember) {
	
	int age = COOKIE_MAX_AGE;
	if (ifRemember) {
		age = COOKIE_MAX_AGE;
	} else {
		age = -1;
	}
	
	Cookie cookie = new Cookie(key, value);
	cookie.setMaxAge(age);				// Cookie过期时间,单位/秒
	cookie.setPath(COOKIE_PATH);		// Cookie适用的路径
	response.addCookie(cookie);
}
 
Example 18
Project: SpringBoot_Wechat_Sell   File: SellerAuthorizeAspect.java   View source code 6 votes vote down vote up
@Before("verify()")
public void doVerify() {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    //查询cookie
    Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
    if (cookie == null) {
        log.warn("【登录校验】Cookie中查不到token");
        throw new SellerAuthorizeException();
    }

    //去redis里查询
    String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
    if (StringUtils.isEmpty(tokenValue)) {
        log.warn("【登录校验】Redis中查不到token");
        throw new SellerAuthorizeException();
    }
}
 
Example 19
Project: syndesis   File: CredentialFlowStateHelperTest.java   View source code 6 votes vote down vote up
@Test
public void shouldRestoreCookiesToStreamOfState() {
    final CredentialFlowState expected1 = new OAuth2CredentialFlowState.Builder().connectorId("connectorId")
        .key("key1").build();
    final CredentialFlowState expected2 = new OAuth2CredentialFlowState.Builder().connectorId("connectorId")
        .key("key2").build();

    final Cookie cookie1 = new Cookie(CredentialFlowState.CREDENTIAL_PREFIX + "key1", "anyValue");
    final Cookie cookie2 = new Cookie(CredentialFlowState.CREDENTIAL_PREFIX + "key2", "anyValue");

    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getCookies()).thenReturn(new Cookie[] {cookie1, cookie2});

    when(request.getCookies()).thenReturn(new Cookie[] {cookie1, cookie2});
    final Set<CredentialFlowState> states = CredentialFlowStateHelper.restoreFrom((cookies, cls) -> {
        assertThat(cookies).allSatisfy(cookie -> assertThat(cookie.getValue()).isEqualTo("anyValue"));

        return cookies.stream()
            .map(cookie -> new OAuth2CredentialFlowState.Builder().connectorId("connectorId")
                .key(cookie.getName().substring(CredentialFlowState.CREDENTIAL_PREFIX.length())).build())
            .collect(Collectors.toSet());
    }, request);

    assertThat(states).containsOnly(expected1, expected2);
}
 
Example 20
Project: spring_mybatis_shiro   File: CookieUtils.java   View source code 6 votes vote down vote up
/**
 * 获取cookie
 * 
 * @param request
 *            HttpServletRequest
 * @param name
 *            cookie名称
 * @return 若不存在则返回null
 */
public static String getCookie(HttpServletRequest request, String name) {
	Assert.notNull(request);
	Assert.hasText(name);
	Cookie[] cookies = request.getCookies();
	if (cookies != null) {
		try {
			name = URLEncoder.encode(name, "UTF-8");
			for (Cookie cookie : cookies) {
				if (name.equals(cookie.getName())) {
					return URLDecoder.decode(cookie.getValue(), "UTF-8");
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	return null;
}
 
Example 21
Project: parabuild-ci   File: BasePage.java   View source code 5 votes vote down vote up
/**
 * Returns status view selection, if any, based on
 * parameters, the session or the cookie.
 */
protected final String getClientParameter(final Parameters params, final HttpServletRequest request,
                                          final String parameterName, final String sessionParameterName,
                                          final String cookieName) {
  String result = params.getParameterValue(parameterName);
  if (!StringUtils.isBlank(result)) {
    return result;
  }

  result = request.getParameter(parameterName);
  if (!StringUtils.isBlank(result)) {
    return result;
  }

  final HttpSession session = request.getSession();
  result = (String) session.getAttribute(sessionParameterName);
  if (!StringUtils.isBlank(result)) {
    return result;
  }

  final Cookie[] cookies = request.getCookies();
  if (cookies != null) {
    for (int i = 0; i < cookies.length; i++) {
      final Cookie cookie = cookies[i];
      if (!StringUtils.isBlank(cookie.getName())
              && cookie.getName().equals(cookieName)
              && !StringUtils.isBlank(cookie.getValue())) {
        result = cookie.getValue();
        break;
      }
    }
  }
  return result;
}
 
Example 22
Project: jwala   File: IndexControllerTest.java   View source code 5 votes vote down vote up
public void testDevModeFalse() {
    HttpServletResponse resp = mock(HttpServletResponse.class);
    ModelAndView mv = ic.devMode("false", resp);
    verify(resp).addCookie(any(Cookie.class));
    assertNotNull(mv);
    assertEquals("{devMode=false}", mv.getModel().toString());
}
 
Example 23
Project: cas4.0.x-server-wechat   File: CookieRetrievingCookieGeneratorTests.java   View source code 5 votes vote down vote up
@Test
public void testCookieAddWithRememberMe() {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.addParameter(RememberMeCredential.REQUEST_PARAMETER_REMEMBER_ME, "true");
    final MockHttpServletResponse response = new MockHttpServletResponse();

    this.g.addCookie(request, response, "test");

    final Cookie c = response.getCookie("test");
    assertEquals(100, c.getMaxAge());
    assertEquals("test", c.getValue());
}
 
Example 24
Project: DAT104   File: RegistrerUtil.java   View source code 5 votes vote down vote up
public static void sjekkCookies(List<Cookie> cookies, HttpServletRequest request) {
	HashMap<String, String> feilmeldinger = new HashMap<>();
	String[] meldinger = { FEIL_FORNAVN, FEIL_ETTERNAVN, FEIL_MOBIL };
	for (int i = 0; i < cookies.size() - 1; i++) {
		String navn = cookies.get(i).getName();
		String verdi = cookies.get(i).getValue();
		if (!sjekkParams(navn, verdi)) {
			feilmeldinger.put(navn, meldinger[i]);
		}
	}
	request.getSession().setAttribute("feilmeldinger", feilmeldinger);
}
 
Example 25
Project: docs-manage   File: JwtHelper.java   View source code 5 votes vote down vote up
/**
 * 获取指定名称的Cookie
 * @param request 请求
 * @param name Cookie名
 * @return 指定Cookie
 */
public Cookie getCookieValue(HttpServletRequest request, String name) {
    if (request.getCookies() == null) {
        return null;
    }
    for (Cookie cookie : request.getCookies()) {
        if (StringUtils.equals(cookie.getName(), name)) {
            return cookie;
        }
    }
    return null;
}
 
Example 26
Project: session-to-cookie   File: SessionToCookieFilter.java   View source code 5 votes vote down vote up
/**
 * returns the cookie corresponding to {@link #getSessionDataCookieName()},
 * if it exists. Null otherwise.
 * 
 * @param httpServletRequest
 * @return
 */
protected Cookie retrieveSessionDataCookie(HttpServletRequest httpServletRequest) {
	Cookie[] cookies = httpServletRequest.getCookies();
	if (cookies != null) {
		for (Cookie cookie : cookies) {
			if (getSessionDataCookieName().equals(cookie.getName())) {
				return cookie;
			}
		}
	}
	return null;
}
 
Example 27
Project: incubator-servicecomb-java-chassis   File: CommonToHttpServletRequest.java   View source code 5 votes vote down vote up
@Override
public Cookie[] getCookies() {
  if (cookies == null) {
    cookies = createCookies();
  }

  return cookies;
}
 
Example 28
Project: github-test   File: Providers.java   View source code 5 votes vote down vote up
/**
 * 设置search记录到cookie中,操作步骤:
 * 检查加入的记录是否已经存在cookie中,如果存在,则更新列表次序;如果不存在,则插入到最前面
 *
 * @param context
 * @param value
 */
private void setSearchHistroy(Map<String, Object> context, String value) {
    //分析已有的cookie
    String separatorsB = "\\.\\.\\.\\.\\.\\.";
    String newCookiev = value;
    Cookie[] cookies = request.getCookies();
    for (Cookie c : cookies) {
        if (c.getName().equals("HISTORY")) {
            String cookiev = c.getValue();
            String[] values = cookiev.split(separatorsB);
            int count = 1;
            for (String v : values) {
                if (count <= 10) {
                    if (!value.equals(v)) {
                        newCookiev = newCookiev + separatorsB + v;
                    }
                }
                count++;
            }
            break;
        }
    }

    Cookie _cookie = new Cookie("HISTORY", newCookiev);
    _cookie.setMaxAge(60 * 60 * 24 * 7); // 设置Cookie的存活时间为30分钟
    _cookie.setPath("/");
    response.addCookie(_cookie); // 写入客户端硬盘
}
 
Example 29
Project: DWSurvey   File: CookieUtils.java   View source code 5 votes vote down vote up
/**
 * @param request
 * @param cookieName
 * @return 指定的cookie
 */
public static Cookie getCookie(HttpServletRequest request, String cookieName) {
	Cookie[] cookies = request.getCookies();
	if (cookies == null) {
		return null;
	}

	for (Cookie c : cookies) {
		if (c.getName().equals(cookieName)) {
			return c;
		}
	}

	return null;
}
 
Example 30
Project: Pet-Supply-Store   File: AbstractUIServlet.java   View source code 5 votes vote down vote up
/**
 * Destroys the SessionBlob. Throws an IllegalStateException if the SessionBlob
 * is corrupted.
 * 
 * @param blob
 * @param response
 */
protected void destroySessionBlob(SessionBlob blob, HttpServletResponse response) {
	ObjectMapper o = new ObjectMapper();
	try {
		Cookie cookie = new Cookie(BLOB, URLEncoder.encode(o.writeValueAsString(blob), "UTF-8"));
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	} catch (JsonProcessingException | UnsupportedEncodingException e) {
		throw new IllegalStateException("Could not destroy blob!");
	}
}
 
Example 31
Project: session-share   File: SessionImpl.java   View source code 5 votes vote down vote up
private Cookie getCookie() {
    Cookie[] cookies = this.httpServletRequest.getCookies();
    if (null != cookies) {
        for (Cookie cookie_ : cookies) {
            if (cookie_.getName().equals(sessionCookieName)) {
                return cookie_;
            }
        }
    }
    return null;
}
 
Example 32
Project: xxl-api   File: CookieInterceptor.java   View source code 5 votes vote down vote up
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
		ModelAndView modelAndView) throws Exception {
	
	if (modelAndView!=null && ArrayUtils.isNotEmpty(request.getCookies())) {
		HashMap<String, Cookie> cookieMap = new HashMap<String, Cookie>();
		for (Cookie ck : request.getCookies()) {
			cookieMap.put(ck.getName(), ck);
		}
		modelAndView.addObject("cookieMap", cookieMap);
	}
	
	super.postHandle(request, response, handler, modelAndView);
}
 
Example 33
Project: spring_mvc_template   File: CookieUtil.java   View source code 5 votes vote down vote up
public static Cookie getCookie(HttpServletRequest request, String name) {
	Cookie[] cookies = request.getCookies();
	if (cookies != null) {
		for (Cookie cookie : cookies) {
			if (name != null && cookie.getName().equals(name)) {
				return cookie;
			}
		}
	}
	return null;
}
 
Example 34
Project: Spring-web-shop-project   File: CookiesDAO.java   View source code 5 votes vote down vote up
public static void deleteCookiesIfDoeasntExists(HttpServletRequest request, HttpServletResponse response) {
    for (Cookie x : request.getCookies()) {
        if (x.getName().equals("JSESSIONID"))
            continue;
        Cookie cookie = new Cookie(x.getName(), x.getValue());
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }
}
 
Example 35
Project: springboot-shiro-cas-mybatis   File: LogoutActionTests.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void verifyLogoutRequestFront() throws Exception {
    final Cookie cookie = new Cookie(COOKIE_TGC_ID, "test");
    this.request.setCookies(cookie);
    final LogoutRequest logoutRequest = new DefaultLogoutRequest("", null, null);
    WebUtils.putLogoutRequests(this.requestContext, Arrays.asList(logoutRequest));
    final Event event = this.logoutAction.doExecute(this.requestContext);
    assertEquals(LogoutAction.FRONT_EVENT, event.getId());
    final List<LogoutRequest> logoutRequests = WebUtils.getLogoutRequests(this.requestContext);
    assertEquals(1, logoutRequests.size());
    assertEquals(logoutRequest, logoutRequests.get(0));
}
 
Example 36
Project: dubbocloud   File: ParameterMap.java   View source code 5 votes vote down vote up
private Object getCookieValue(String key) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        for (Cookie cookie : cookies) {
            if (key.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
    }
    return null;
}
 
Example 37
Project: spring-rest-sample   File: CrossDomainSessionController.java   View source code 5 votes vote down vote up
/**
 * 创建cookie
 * @param response
 * @return
 */
@RequestMapping(value = "/create", method = RequestMethod.GET)
@ResponseBody
public PrevalentMessage createSession(HttpServletResponse response) {

    Cookie cookie = new Cookie("token", UUID.randomUUID().toString());
    cookie.setPath("/");
    cookie.setSecure(false);
    cookie.setHttpOnly(true);
    cookie.setMaxAge(86400);
    cookie.setValue("test");
    response.addCookie(cookie);

    return new PrevalentMessage("ok");
}
 
Example 38
Project: karate   File: HeadersController.java   View source code 5 votes vote down vote up
@GetMapping
public ResponseEntity getToken(HttpServletResponse response) {
    String token = UUID.randomUUID().toString();
    String time = System.currentTimeMillis() + "";
    tokens.put(token, time);
    response.addCookie(new Cookie("time", time));
    return ResponseEntity.ok().body(token);
}
 
Example 39
Project: syndesis   File: CredentialHandler.java   View source code 5 votes vote down vote up
static void removeCredentialCookies(final HttpServletRequest request,
    final HttpServletResponse response) {
    Arrays.stream(request.getCookies()).filter(c -> c.getName().startsWith(CredentialFlowState.CREDENTIAL_PREFIX))
        .forEach(c -> {
            final Cookie removal = new Cookie(c.getName(), "");
            removal.setPath("/");
            removal.setMaxAge(0);
            removal.setHttpOnly(true);
            removal.setSecure(true);

            response.addCookie(removal);
        });
}
 
Example 40
Project: gitplex-mit   File: AdvancedSearchPanel.java   View source code 5 votes vote down vote up
private void onSelectTab(AjaxRequestTarget target) {
	WebResponse response = (WebResponse) RequestCycle.get().getResponse();
	Cookie cookie = new Cookie(COOKIE_SEARCH_TYPE, option.getClass().getName());
	cookie.setMaxAge(Integer.MAX_VALUE);
	response.addCookie(cookie);
	SearchOptionEditor editor = newSearchOptionEditor(option);
	form.replace(editor);
	target.add(editor);
}