javax.servlet.http.Cookie Java Examples
The following examples show how to use
javax.servlet.http.Cookie.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RedirectScopeManager.java From ozark with Apache License 2.0 | 6 votes |
/** * Update SCOPE_ID request attribute based on either cookie or URL query param * information received in the request. * * @param event the event. */ public void beforeProcessControllerEvent(@Observes BeforeControllerEvent event) { if (usingCookies()) { final Cookie[] cookies = request.getCookies(); if (null != cookies) { for (Cookie cookie : cookies) { if (cookie.getName().equals(COOKIE_NAME)) { request.setAttribute(SCOPE_ID, cookie.getValue()); return; // we're done } } } } else { final String scopeId = event.getUriInfo().getQueryParameters().getFirst(SCOPE_ID); if (scopeId != null) { request.setAttribute(SCOPE_ID, scopeId); } } }
Example #2
Source File: PullRequestActivitiesPage.java From onedev with MIT License | 6 votes |
public PullRequestActivitiesPage(PageParameters params) { super(params); WebRequest request = (WebRequest) RequestCycle.get().getRequest(); Cookie cookie = request.getCookie(COOKIE_SHOW_COMMENTS); if (cookie != null) showComments = Boolean.valueOf(cookie.getValue()); cookie = request.getCookie(COOKIE_SHOW_COMMITS); if (cookie != null) showCommits = Boolean.valueOf(cookie.getValue()); cookie = request.getCookie(COOKIE_SHOW_CHANGE_HISTORY); if (cookie != null) showChangeHistory = Boolean.valueOf(cookie.getValue()); }
Example #3
Source File: CookieUtils.java From express-ssm with Apache License 2.0 | 6 votes |
/** * 得到Cookie的值 * @author jitwxs * @version 创建时间:2018年4月16日 下午7:08:13 * @param isDecoder 是否编码,编码格式为UTF-8 */ public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) { Cookie[] cookieList = request.getCookies(); if (cookieList == null || cookieName == null) { return null; } String retValue = null; try { for (int i = 0; i < cookieList.length; i++) { if (cookieList[i].getName().equals(cookieName)) { if (isDecoder) { retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8"); } else { retValue = cookieList[i].getValue(); } break; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return retValue; }
Example #4
Source File: WebUtils.java From open-cloud with MIT License | 6 votes |
/** * 获得指定Cookie的值 * * @param request 请求对象 * @param response 响应对象 * @param name 名字 * @param isRemove 是否移除 * @return 值 */ public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name, boolean isRemove) { String value = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(name)) { try { value = URLDecoder.decode(cookie.getValue(), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (isRemove) { cookie.setMaxAge(0); response.addCookie(cookie); } } } } return value; }
Example #5
Source File: CookieServlet.java From spiracle with Apache License 2.0 | 6 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String name = req.getParameter("cookieName"); String value = req.getParameter("cookieValue"); String secure = req.getParameter("secure"); String path = req.getParameter("cookiePath"); Cookie cookie = new Cookie(name, value); if (secure.equals("yes")) { cookie.setSecure(true); } if (path != null) { cookie.setPath(path); } res.addCookie(cookie); RequestDispatcher requestDispatcher = req .getRequestDispatcher("/cookie.jsp"); requestDispatcher.forward(req, res); }
Example #6
Source File: CookieUtils.java From express-ssm with Apache License 2.0 | 6 votes |
private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, String encodeString) { try { if (cookieValue == null) { cookieValue = ""; } else { cookieValue = URLEncoder.encode(cookieValue, encodeString); } Cookie cookie = new Cookie(cookieName, cookieValue); if (cookieMaxage > 0) cookie.setMaxAge(cookieMaxage); if (null != request) {// 设置域名的cookie String domainName = getDomainName(request); // System.out.println(domainName); if (!"localhost".equals(domainName)) { cookie.setDomain(domainName); } } cookie.setPath("/"); response.addCookie(cookie); } catch (Exception e) { e.printStackTrace(); } }
Example #7
Source File: WebUtils.java From phone with Apache License 2.0 | 6 votes |
/** * 根据键读取cookie的值 * * @param request 请求对象 * @param key 读取cookie的键 * @return cookie的值 */ public static String readCookie(HttpServletRequest request, String key) { Cookie[] cookies = request.getCookies(); if (cookies != null&&key!=null) { for (Cookie cookie : cookies) { if (cookie != null && key.equalsIgnoreCase(cookie.getName())) { try { String value = URLDecoder.decode(cookie.getValue(), SystemConfig.CHARSET); return value; } catch (UnsupportedEncodingException e) { } } } } return null; }
Example #8
Source File: LogoutServlet.java From journaldev with MIT License | 6 votes |
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); Cookie[] cookies = request.getCookies(); if(cookies != null){ for(Cookie cookie : cookies){ if(cookie.getName().equals("JSESSIONID")){ System.out.println("JSESSIONID="+cookie.getValue()); } cookie.setMaxAge(0); response.addCookie(cookie); } } //invalidate the session if exists HttpSession session = request.getSession(false); System.out.println("User="+session.getAttribute("user")); if(session != null){ session.invalidate(); } //no encoding because we have invalidated the session response.sendRedirect("login.html"); }
Example #9
Source File: MockHttpClient.java From karate with MIT License | 6 votes |
@Override protected void buildCookie(com.intuit.karate.http.Cookie c) { Cookie cookie = new Cookie(c.getName(), c.getValue()); requestBuilder.cookie(cookie); for (Map.Entry<String, String> entry : c.entrySet()) { if (entry.getValue() != null) { switch (entry.getKey()) { case DOMAIN: cookie.setDomain(entry.getValue()); break; case PATH: cookie.setPath(entry.getValue()); break; } } } if (cookie.getDomain() == null) { cookie.setDomain(uri.getHost()); } }
Example #10
Source File: ServletCookieValueMethodArgumentResolver.java From java-technology-stack with MIT License | 6 votes |
@Override @Nullable protected Object resolveName(String cookieName, MethodParameter parameter, NativeWebRequest webRequest) throws Exception { HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class); Assert.state(servletRequest != null, "No HttpServletRequest"); Cookie cookieValue = WebUtils.getCookie(servletRequest, cookieName); if (Cookie.class.isAssignableFrom(parameter.getNestedParameterType())) { return cookieValue; } else if (cookieValue != null) { return this.urlPathHelper.decodeRequestString(servletRequest, cookieValue.getValue()); } else { return null; } }
Example #11
Source File: WebSSOutResource.java From knox with Apache License 2.0 | 6 votes |
private boolean removeAuthenticationToken(HttpServletResponse response) { boolean rc = true; Cookie c = new Cookie(cookieName, null); c.setMaxAge(0); c.setPath("/"); try { String domainName = Urls.getDomainName(request.getRequestURL().toString(), null); if(domainName != null) { c.setDomain(domainName); } } catch (MalformedURLException e) { log.problemWithCookieDomainUsingDefault(); // we are probably not going to be able to // remove the cookie due to this error but it // isn't necessarily not going to work. rc = false; } response.addCookie(c); return rc; }
Example #12
Source File: AdminPageController.java From zrlog with Apache License 2.0 | 6 votes |
public void logout() { Cookie[] cookies = getRequest().getCookies(); for (Cookie cookie : cookies) { if ("zId".equals(cookie.getName())) { cookie.setValue(""); cookie.setMaxAge(Constants.getSessionTimeout().intValue()); getResponse().addCookie(cookie); } if (Constants.ADMIN_TOKEN.equals(cookie.getName())) { cookie.setValue(""); cookie.setMaxAge(Constants.getSessionTimeout().intValue()); cookie.setPath("/"); adminTokenService.setCookieDomain(getRequest(), cookie); getResponse().addCookie(cookie); } } redirect(LOGOUT_URI); }
Example #13
Source File: AdminTokenService.java From zrlog with Apache License 2.0 | 6 votes |
public void setAdminToken(User user, int sessionId, String protocol, HttpServletRequest request, HttpServletResponse response) { AdminTokenVO adminTokenVO = new AdminTokenVO(); adminTokenVO.setUserId(user.getInt("userId")); adminTokenVO.setSessionId(sessionId); adminTokenVO.setProtocol(protocol); long loginTime = System.currentTimeMillis(); adminTokenVO.setCreatedDate(loginTime); AdminTokenThreadLocal.setAdminToken(adminTokenVO); String encryptBeforeString = new Gson().toJson(adminTokenVO); try { byte[] base64Bytes = Base64.encodeBase64(encrypt(user.get("secretKey").toString(), encryptBeforeString.getBytes())); String encryptAfterString = ByteUtils.bytesToHexString(base64Bytes); String finalTokenString = adminTokenVO.getUserId() + TOKEN_SPLIT_CHAR + encryptAfterString; Cookie cookie = new Cookie(Constants.ADMIN_TOKEN, finalTokenString); cookie.setMaxAge((int) (Constants.getSessionTimeout() / 1000)); setCookieDomain(request, cookie); cookie.setPath("/"); response.addCookie(cookie); } catch (Exception e) { LOGGER.error("", e); } }
Example #14
Source File: TokenAuthenticationHelper.java From spring-security-jwt-csrf with MIT License | 6 votes |
static Authentication getAuthentication(HttpServletRequest request) { Cookie cookie = WebUtils.getCookie(request, COOKIE_BEARER); String token = cookie != null ? cookie.getValue() : null; if (token != null) { Claims claims = Jwts.parser() .setSigningKey(SECRET) .parseClaimsJws(token) .getBody(); Collection<? extends GrantedAuthority> authorities = Arrays.stream(claims.get("authorities").toString().split(",")) .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); String userName = claims.getSubject(); return userName != null ? new UsernamePasswordAuthenticationToken(userName, null, authorities) : null; } return null; }
Example #15
Source File: SessionBeanTest.java From development with Apache License 2.0 | 6 votes |
@Before public void setUp() throws Exception { sessionBean = spy(new SessionBean()); doReturn(MARKETPLACE_ID).when(sessionBean).getMarketplaceId(); // Mock the faces context of the SessionBean fcContextMock = mock(FacesContext.class); doReturn(fcContextMock).when(sessionBean).getFacesContext(); // Mock the external context of the faces context ExternalContext extContextMock = mock(ExternalContext.class); doReturn(extContextMock).when(fcContextMock).getExternalContext(); doReturn(WHITE_LABEL_PATH).when(extContextMock).getRequestContextPath(); req = mock(HttpServletRequest.class); doReturn(req).when(extContextMock).getRequest(); doReturn(req).when(sessionBean).getRequest(); // Mock the marketplace service marketplaceServiceMock = mock(MarketplaceService.class); doReturn(marketplaceServiceMock).when(sessionBean) .getMarketplaceService(); cookies = new Cookie[1]; doReturn(cookies).when(req).getCookies(); }
Example #16
Source File: CookieHelper.java From kisso with Apache License 2.0 | 6 votes |
/** * <p> * 清除指定Cookie 等同于 clearCookieByName(...) * </p> * <p> * <p> * 该方法不判断Cookie是否存在,因此不对外暴露防止Cookie不存在异常. * </p> * * @param response * @param cookieName cookie name * @param domain Cookie所在的域 * @param path Cookie 路径 * @return boolean */ private static boolean clearCookie(HttpServletResponse response, String cookieName, String domain, String path) { boolean result = false; try { Cookie cookie = new Cookie(cookieName, ""); cookie.setMaxAge(CLEAR_IMMEDIATELY_REMOVE); if (StringUtils.isNotEmpty(domain)) { cookie.setDomain(domain); } cookie.setPath(path); response.addCookie(cookie); log.debug("clear cookie " + cookieName); result = true; } catch (Exception e) { log.error("clear cookie " + cookieName + " is exception!\n" + e.toString()); } return result; }
Example #17
Source File: HttpProxy.java From haven-platform with Apache License 2.0 | 6 votes |
/** * Copy cookie from the proxy to the servlet client. * Replaces cookie path to local path and renames cookie to avoid collisions. */ private 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 (int i = 0, l = cookies.size(); i < l; i++) { HttpCookie cookie = cookies.get(i); //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 #18
Source File: CookieUtils.java From learning-taotaoMall with MIT License | 6 votes |
/** * 得到Cookie的值, * * @param request * @param cookieName * @return */ public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) { Cookie[] cookieList = request.getCookies(); if (cookieList == null || cookieName == null) { return null; } String retValue = null; try { for (int i = 0; i < cookieList.length; i++) { if (cookieList[i].getName().equals(cookieName)) { if (isDecoder) { retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8"); } else { retValue = cookieList[i].getValue(); } break; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return retValue; }
Example #19
Source File: RememberMeSecurityConfigurationTests.java From spring-session with Apache License 2.0 | 5 votes |
@Test void authenticateWhenSpringSessionRememberMeEnabledThenCookieMaxAgeAndSessionExpirationSet() throws Exception { // @formatter:off MvcResult result = this.mockMvc .perform(formLogin()) .andReturn(); // @formatter:on Cookie cookie = result.getResponse().getCookie("SESSION"); assertThat(cookie.getMaxAge()).isEqualTo(Integer.MAX_VALUE); T session = this.sessions.findById(new String(Base64.getDecoder().decode(cookie.getValue()))); assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofDays(30)); }
Example #20
Source File: RequestImpl.java From knopflerfish.org with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public Cookie[] getCookies() { Dictionary<String, Cloneable> d; if (cookies == null && !(d = base.getCookies()).isEmpty()) { cookies = new Cookie[d.size()]; final Enumeration<Cloneable> e = d.elements(); for (int i = 0; i < cookies.length; i++) { cookies[i] = (Cookie) e.nextElement(); } } return cookies; }
Example #21
Source File: CookieSerializer.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
@SuppressWarnings("RedundantIfStatement") static boolean equals(final Cookie thisCookie, final Cookie thatCookie) { if (thisCookie.getMaxAge() != thatCookie.getMaxAge()) { return false; } if (thisCookie.getSecure() != thatCookie.getSecure()) { return false; } if (thisCookie.getVersion() != thatCookie.getVersion()) { return false; } if (thisCookie.getName() != null ? !thisCookie.getName().equals( thatCookie.getName()) : thatCookie.getName() != null) { return false; } if (thisCookie.getValue() != null ? !thisCookie.getValue().equals( thatCookie.getValue()) : thatCookie.getValue() != null) { return false; } if (thisCookie.getComment() != null ? !thisCookie.getComment().equals( thatCookie.getComment()) : thatCookie.getComment() != null) { return false; } if (thisCookie.getDomain() != null ? !thisCookie.getDomain().equals( thatCookie.getDomain()) : thatCookie.getDomain() != null) { return false; } if (thisCookie.getPath() != null ? !thisCookie.getPath().equals( thatCookie.getPath()) : thatCookie.getPath() != null) { return false; } return true; }
Example #22
Source File: CookieMacro.java From engine with GNU General Public License v3.0 | 5 votes |
@Override protected String getMacroValue(String str) { RequestContext requestContext = RequestContext.getCurrent(); if (requestContext != null) { Cookie cookie = HttpUtils.getCookie(cookieName, requestContext.getRequest()); if (cookie != null) { return cookie.getValue(); } } return null; }
Example #23
Source File: HtmlUnitRequestBuilder.java From java-technology-stack with MIT License | 5 votes |
private void processCookie(MockHttpServletRequest request, List<Cookie> cookies, Cookie cookie) { cookies.add(cookie); if ("JSESSIONID".equals(cookie.getName())) { request.setRequestedSessionId(cookie.getValue()); request.setSession(httpSession(request, cookie.getValue())); } }
Example #24
Source File: LeakedHttpOnlyCookie.java From firing-range with Apache License 2.0 | 5 votes |
private Optional<String> getCookieValueByName(HttpServletRequest request, String name) { Cookie[] cookies = request.getCookies(); for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals(name)) { return Optional.of(cookies[i].getValue()); } } return Optional.empty(); }
Example #25
Source File: CookieUtils.java From opencron with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") public static Map<String, Cookie> cookieToMap(Cookie[] cookies) { if (cookies == null || cookies.length == 0) return new HashMap(0); Map map = new HashMap(cookies.length * 2); for (Cookie c : cookies) { map.put(c.getName(), c); } return map; }
Example #26
Source File: TestCookieProcessor.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Test public void testGetValueCookiesNotFound() throws Exception { Cookie[] cookies = new Cookie[] {new Cookie("c1", "c1v")}; new Expectations() { { request.getCookies(); result = cookies; } }; CookieProcessor processor = createProcessor("c2", String.class, null, false); Object value = processor.getValue(request); Assert.assertNull(value); }
Example #27
Source File: PageProcessAspect.java From MicroCommunity with Apache License 2.0 | 5 votes |
/** * 获取TOKEN * * @param request * @return */ private String getToken(HttpServletRequest request) throws FilterException { String token = ""; if (request.getCookies() == null || request.getCookies().length == 0) { return token; } for (Cookie cookie : request.getCookies()) { if (CommonConstant.COOKIE_AUTH_TOKEN.equals(cookie.getName())) { token = cookie.getValue(); } } return token; }
Example #28
Source File: SessionInterceptor.java From NoteBlog with MIT License | 5 votes |
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Cookie cookie = CookieUtils.getCookie(request, SessionParam.SESSION_ID_COOKIE); if (cookie != null) { String sessionId = cookie.getValue(); User sessionUser = blogContext.getSessionUser(sessionId); if (sessionUser == null) { Cookie rememberCookie = CookieUtils.getCookie(request, REMEMBER_COOKIE_NAME); if (rememberCookie != null) { String userString = rememberCookie.getValue(); try { String username = userString.split(COOKIE_SPLIT)[0]; String password = userString.split(COOKIE_SPLIT)[1]; User cookieUser = userRepository.findByUsernameAndPasswordAndEnable(base64.decodeStr(username), password, true); if (cookieUser != null) { blogContext.setSessionUser(request, response, cookieUser); log.info("[已登录用户]"); return true; } } catch (Exception ignore) { } } log.info("[未登录用户]"); if (WebUtils.isAjaxRequest(request)) { response.setCharacterEncoding("UTF-8"); response.getWriter().write(JsonSerializer.create().serialize(error("用户未登录或登录时效过期,请重新登录!", LOGIN_URL))); } else { response.sendRedirect(LOGIN_URL); } return false; } else { log.info("[已登录用户]"); return true; } } else { response.sendRedirect(LOGIN_URL); return false; } }
Example #29
Source File: PostViewCounter.java From mamute with Apache License 2.0 | 5 votes |
private boolean recentlyViewed(ViewCountable post) { Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals(cookieKeyFor(post))) { return true; } } return false; }
Example #30
Source File: HttpHelper.java From Albianj2 with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static String getCookieValue(HttpServletRequest request, String name) { Cookie cookie = getCookie(request, name); if (cookie != null) { return cookie.getValue(); } return null; }