當前位置: 首頁>>代碼示例>>Java>>正文


Java Cookie類代碼示例

本文整理匯總了Java中javax.servlet.http.Cookie的典型用法代碼示例。如果您正苦於以下問題:Java Cookie類的具體用法?Java Cookie怎麽用?Java Cookie使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Cookie類屬於javax.servlet.http包,在下文中一共展示了Cookie類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: doFilterInternal

import javax.servlet.http.Cookie; //導入依賴的package包/類
@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);
}
 
開發者ID:GastonMauroDiaz,項目名稱:buenojo,代碼行數:19,代碼來源:CsrfCookieGeneratorFilter.java

示例2: getCookie

import javax.servlet.http.Cookie; //導入依賴的package包/類
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;
}
 
開發者ID:liaokailin,項目名稱:tomcat7,代碼行數:36,代碼來源:ImplicitObjectELResolver.java

示例3: deleteCookie

import javax.servlet.http.Cookie; //導入依賴的package包/類
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);
    }
}
 
開發者ID:bridgeli,項目名稱:netty-socketio-demo,代碼行數:13,代碼來源:CookieUtils.java

示例4: getCookie

import javax.servlet.http.Cookie; //導入依賴的package包/類
/**
 * 從 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;
}
 
開發者ID:smxc,項目名稱:garlicts,代碼行數:22,代碼來源:WebUtil.java

示例5: getGidCookie

import javax.servlet.http.Cookie; //導入依賴的package包/類
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;
}
 
開發者ID:wxz1211,項目名稱:dooo,代碼行數:21,代碼來源:UserAuth.java

示例6: getToken

import javax.servlet.http.Cookie; //導入依賴的package包/類
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;
}
 
開發者ID:bfwg,項目名稱:angular-spring-starter,代碼行數:20,代碼來源:TokenHelper.java

示例7: containsKey

import javax.servlet.http.Cookie; //導入依賴的package包/類
@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;
}
 
開發者ID:apache,項目名稱:myfaces-trinidad,代碼行數:19,代碼來源:ServletCookieMap.java

示例8: testGetValueCookiesDate

import javax.servlet.http.Cookie; //導入依賴的package包/類
@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));
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-java-chassis,代碼行數:17,代碼來源:TestCookieProcessor.java

示例9: getCookies

import javax.servlet.http.Cookie; //導入依賴的package包/類
@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;
}
 
開發者ID:sunmingshuai,項目名稱:apache-tomcat-7.0.73-with-comment,代碼行數:27,代碼來源:RequestFacade.java

示例10: copyProxyCookie

import javax.servlet.http.Cookie; //導入依賴的package包/類
/**
 * 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);
    }
}
 
開發者ID:bluecreator,項目名稱:http-agent,代碼行數:23,代碼來源:AgentServlet.java

示例11: getRememberedDisplayGroupID

import javax.servlet.http.Cookie; //導入依賴的package包/類
/**
   */
  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;
  }
 
開發者ID:parabuild-ci,項目名稱:parabuild-ci,代碼行數:32,代碼來源:BuildsStatusesPage.java

示例12: verifyTgtToSetRemovingOldTgt

import javax.servlet.http.Cookie; //導入依賴的package包/類
@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));
}
 
開發者ID:hsj-xiaokang,項目名稱:springboot-shiro-cas-mybatis,代碼行數:17,代碼來源:SendTicketGrantingTicketActionTests.java

示例13: addCookie

import javax.servlet.http.Cookie; //導入依賴的package包/類
/**
 * 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());
}
 
開發者ID:liaokailin,項目名稱:tomcat7,代碼行數:22,代碼來源:Response.java

示例14: getPlayerIdFromCookie

import javax.servlet.http.Cookie; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:airsonic,項目名稱:airsonic,代碼行數:21,代碼來源:PlayerService.java

示例15: addCookie

import javax.servlet.http.Cookie; //導入依賴的package包/類
/**添加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;
}
 
開發者ID:zhangjikai,項目名稱:sdudoc,代碼行數:14,代碼來源:CookieUtil.java


注:本文中的javax.servlet.http.Cookie類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。