java类javax.servlet.http.Cookie的实例源码

ImplicitObjectELResolver.java 文件源码 项目:tomcat7 阅读 36 收藏 0 点赞 0 评论 0
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;
}
CookieUtils.java 文件源码 项目:netty-socketio-demo 阅读 34 收藏 0 点赞 0 评论 0
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);
    }
}
CsrfCookieGeneratorFilter.java 文件源码 项目:shoucang 阅读 37 收藏 0 点赞 0 评论 0
@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);
}
CsrfCookieGeneratorFilter.java 文件源码 项目:buenojo 阅读 38 收藏 0 点赞 0 评论 0
@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);
}
WebUtil.java 文件源码 项目:garlicts 阅读 45 收藏 0 点赞 0 评论 0
/**
 * 从 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;
}
UserAuth.java 文件源码 项目:dooo 阅读 28 收藏 0 点赞 0 评论 0
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;
}
TokenHelper.java 文件源码 项目:angular-spring-starter 阅读 37 收藏 0 点赞 0 评论 0
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;
}
ServletCookieMap.java 文件源码 项目:myfaces-trinidad 阅读 28 收藏 0 点赞 0 评论 0
@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;
}
TestCookieProcessor.java 文件源码 项目:incubator-servicecomb-java-chassis 阅读 31 收藏 0 点赞 0 评论 0
@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));
}
RequestFacade.java 文件源码 项目:apache-tomcat-7.0.73-with-comment 阅读 31 收藏 0 点赞 0 评论 0
@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;
}
AgentServlet.java 文件源码 项目:http-agent 阅读 32 收藏 0 点赞 0 评论 0
/**
 * 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);
    }
}
BuildsStatusesPage.java 文件源码 项目:parabuild-ci 阅读 35 收藏 0 点赞 0 评论 0
/**
   */
  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;
  }
SendTicketGrantingTicketActionTests.java 文件源码 项目:springboot-shiro-cas-mybatis 阅读 37 收藏 0 点赞 0 评论 0
@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));
}
Response.java 文件源码 项目:tomcat7 阅读 41 收藏 0 点赞 0 评论 0
/**
 * 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());
}
CookieUtil.java 文件源码 项目:sdudoc 阅读 45 收藏 0 点赞 0 评论 0
/**添加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;
}
CookieUtil.java 文件源码 项目:stage-job 阅读 45 收藏 0 点赞 0 评论 0
/**
 * 保存
 * @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);
}
SellerAuthorizeAspect.java 文件源码 项目:SpringBoot_Wechat_Sell 阅读 30 收藏 0 点赞 0 评论 0
@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();
    }
}
CredentialFlowStateHelperTest.java 文件源码 项目:syndesis 阅读 39 收藏 0 点赞 0 评论 0
@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);
}
CookieUtils.java 文件源码 项目:spring_mybatis_shiro 阅读 32 收藏 0 点赞 0 评论 0
/**
 * 获取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;
}
BasePage.java 文件源码 项目:parabuild-ci 阅读 45 收藏 0 点赞 0 评论 0
/**
 * 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;
}
IndexControllerTest.java 文件源码 项目:jwala 阅读 34 收藏 0 点赞 0 评论 0
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());
}
CookieRetrievingCookieGeneratorTests.java 文件源码 项目:cas4.0.x-server-wechat 阅读 35 收藏 0 点赞 0 评论 0
@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());
}
RegistrerUtil.java 文件源码 项目:DAT104 阅读 42 收藏 0 点赞 0 评论 0
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);
}
JwtHelper.java 文件源码 项目:docs-manage 阅读 71 收藏 0 点赞 0 评论 0
/**
 * 获取指定名称的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;
}
SessionToCookieFilter.java 文件源码 项目:session-to-cookie 阅读 35 收藏 0 点赞 0 评论 0
/**
 * 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;
}
CommonToHttpServletRequest.java 文件源码 项目:incubator-servicecomb-java-chassis 阅读 30 收藏 0 点赞 0 评论 0
@Override
public Cookie[] getCookies() {
  if (cookies == null) {
    cookies = createCookies();
  }

  return cookies;
}
Providers.java 文件源码 项目:github-test 阅读 36 收藏 0 点赞 0 评论 0
/**
 * 设置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); // 写入客户端硬盘
}
CookieUtils.java 文件源码 项目:DWSurvey 阅读 44 收藏 0 点赞 0 评论 0
/**
 * @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;
}
AbstractUIServlet.java 文件源码 项目:Pet-Supply-Store 阅读 35 收藏 0 点赞 0 评论 0
/**
 * 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!");
    }
}
SessionImpl.java 文件源码 项目:session-share 阅读 85 收藏 0 点赞 0 评论 0
private Cookie getCookie() {
    Cookie[] cookies = this.httpServletRequest.getCookies();
    if (null != cookies) {
        for (Cookie cookie_ : cookies) {
            if (cookie_.getName().equals(sessionCookieName)) {
                return cookie_;
            }
        }
    }
    return null;
}


问题


面经


文章

微信
公众号

扫码关注公众号