Java Code Examples for javax.servlet.http.HttpServletRequest.getCookies()

The following are Jave code examples for showing how to use getCookies() of the javax.servlet.http.HttpServletRequest class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: karate   File: SearchController.java   View Source Code Vote up 7 votes
@RequestMapping(value = "/cookies", method = {GET, POST})
public List<Cookie> echoCookies(HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null) {
        return Collections.emptyList();
    } else {
        String domain = request.getParameter("domain");
        for (Cookie cookie: cookies) {
            if (domain != null) {
                cookie.setDomain(domain);
            }
            response.addCookie(cookie);
        }
        return Arrays.asList(cookies);
    }
}
 
Example 2
Project: xbin-store   File: CookieUtils.java   View Source Code Vote up 7 votes
/**
 * 得到Cookie的值,
 * 
 * @param request
 * @param cookieName
 * @return
 */
public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {
    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)) {
                retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);
                break;
            }
        }
    } catch (UnsupportedEncodingException e) {
    	 e.printStackTrace();
    }
    return retValue;
}
 
Example 3
Project: apache-tomcat-7.0.73-with-comment   File: TestCookiesDisallowEquals.java   View Source Code Vote up 6 votes
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
    Cookie cookies[] = req.getCookies();
    for (Cookie cookie : cookies) {
        resp.getWriter().write(cookie.getName() + "=" +
                cookie.getValue() + "\n");
    }
    resp.flushBuffer();
}
 
Example 4
Project: spring_mybatis_shiro   File: CookieUtils.java   View Source Code Vote up 6 votes
/**
 * 获取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 5
Project: lams   File: ImplicitObjectELResolver.java   View Source Code Vote up 6 votes
/**
 *
 * Creates the Map that maps cookie name to the first matching
 * Cookie in request.getCookies().
 **/
public static Map<String, Cookie> createCookieMap (PageContext pContext)
{
  // Read all the cookies and construct the entire map
  HttpServletRequest request = (HttpServletRequest) pContext.getRequest ();
  Cookie [] cookies = request.getCookies ();
  Map<String, Cookie> ret = new HashMap<String, Cookie> ();
  for (int i = 0; cookies != null && i < cookies.length; i++) {
    Cookie cookie = cookies [i];
    if (cookie != null) {
      String name = cookie.getName ();
      if (!ret.containsKey (name)) {
        ret.put (name, cookie);
      }
    }
  }
  return ret;
}
 
Example 6
Project: lemon   File: DeviceFilter.java   View Source Code Vote up 6 votes
public String getCookie(HttpServletRequest request, String key) {
    Cookie[] cookies = request.getCookies();

    if (cookies == null) {
        return null;
    }

    for (Cookie cookie : cookies) {
        if ((cookie == null) || (cookie.getName() == null)) {
            continue;
        }

        if (cookie.getName().equals(key)) {
            return cookie.getValue();
        }
    }

    return null;
}
 
Example 7
Project: lemon-framework   File: CookieUtil.java   View Source Code Vote up 6 votes
/**
 * 销毁所有cookie
 * 
 * @param request
 * @param response
 */
public static void removeAllCookie(HttpServletRequest request, HttpServletResponse response) {
	Cookie[] cookies = request.getCookies();
	if (null != cookies) {
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			cookie.setValue(null);
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}
	}
}
 
Example 8
Project: guice-websocket   File: AuthenticationFilter.java   View Source Code Vote up 5 votes
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    LOGGER.info("Checking client, request: {}", request);

    if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        if (!httpServletRequest.getServletPath().equals("/echo")) {
            chain.doFilter(request, response);
            return;
        }

        Cookie[] cookies = httpServletRequest.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("accessToken") && cookie.getValue().equals("top-secret-token")) {
                    LOGGER.info("Finish checking client - client is authenticated");
                    chain.doFilter(request, response);
                    return;
                }
            }
        }

        LOGGER.warn("Finish checking client - client is unauthenticated !");
        httpServletResponse.setStatus(401);
        httpServletResponse.getWriter().print("Invalid token !");
    }
}
 
Example 9
Project: SpringBoot_Wechat_Sell   File: CookieUtil.java   View Source Code Vote up 5 votes
private static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
    Map<String, Cookie> cookieMap = new HashMap<>();
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            cookieMap.put(cookie.getName(), cookie);
        }
    }
    return cookieMap;
}
 
Example 10
Project: spring-cloud-template   File: LoginController.java   View Source Code Vote up 5 votes
@GetMapping("/logout")
public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null){
        new SecurityContextLogoutHandler().logout(request, response, auth);
    }
    Cookie[] cookies = request.getCookies();
    for(int i = 0,len = cookies.length; i < len; i++) {
        Cookie cookie = new Cookie(cookies[i].getName(),null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
    return "redirect:/";
}
 
Example 11
Project: febit   File: ServletUtil.java   View Source Code Vote up 5 votes
/**
 * Get cookie by name.
 *
 * @param request
 * @param name
 * @return returns null if not found.
 */
public static Cookie getCookie(HttpServletRequest request, String name) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null) {
        return null;
    }
    for (Cookie cookie : cookies) {
        if (cookie.getName().equals(name)) {
            return cookie;
        }
    }
    return null;
}
 
Example 12
Project: Spring-web-shop-project   File: CustomRememberMeServices.java   View Source Code Vote up 5 votes
@Override
public void loginSuccess(HttpServletRequest request, HttpServletResponse response,
                         Authentication successfulAuthentication) {

    User user = RepositoriesAccess.usersRepository
            .findByLogin(SecurityContextHolder.getContext().getAuthentication().getName());

    if (request.getCookies().length > 1)
        CookiesDAO.deleteCurrentCookies(request, response);

    String codeCookieWithCookie = Coder.getUniqueCode();
    String codeCookieWithUser = Coder.getUniqueCode();

    Cookies mainCookie = new Cookies(codeCookieWithCookie, codeCookieWithUser);
    Cookies rememberMeCookie = new Cookies("remember", codeCookieWithCookie);
    user.setCookieCode(codeCookieWithUser);

    Cookie c = new Cookie(mainCookie.getName(), mainCookie.getValue());
    c.setMaxAge(604800);
    response.addCookie(c);
    Cookie c1 = new Cookie("remember", rememberMeCookie.getValue());
    c1.setMaxAge(604800);
    response.addCookie(c1);

    mainCookie.setDate(CookiesDAO.getEndCookieDate(7));
    rememberMeCookie.setDate(CookiesDAO.getEndCookieDate(7));

    RepositoriesAccess.cookiesRepository.save(mainCookie);
    RepositoriesAccess.cookiesRepository.save(rememberMeCookie);
    RepositoriesAccess.usersRepository.save(user);
}
 
Example 13
Project: tomcat7   File: TestCookiesDisallowEquals.java   View Source Code Vote up 5 votes
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
    Cookie cookies[] = req.getCookies();
    for (Cookie cookie : cookies) {
        resp.getWriter().write(cookie.getName() + "=" +
                cookie.getValue() + "\n");
    }
    resp.flushBuffer();
}
 
Example 14
Project: Spring-web-shop-project   File: CustomRememberMeServices.java   View Source Code Vote up 5 votes
@Override
public Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) {
    if (!CookiesDAO.checkCookiesExistsAndDeleteIfNo(request, response))
        return null;
    if (CookiesDAO.isCookieStillActualDeleteIfNo(request, response))
        return null;

    Cookies a = null;
    Cookies a1 = null;
    User user = null;

    if (request.getCookies().length < 2)
        return null;

    for (Cookie x : request.getCookies())
        if (x.getName().equals("remember")) {
            a = RepositoriesAccess.cookiesRepository.findByValue(x.getValue());
            a1 = RepositoriesAccess.cookiesRepository.findByName(x.getValue());
            user = CookiesDAO.findConnectUserWithCookie(a1);
        }

    if (a == null || a1 == null || user == null)
        return null;

    if (user.getCookieCode().equals(a1.getValue()))
        if (a1.getName().equals(a.getValue()))
            return UserDAO.login(user.getLogin(), user.getPassword());
    return null;
}
 
Example 15
Project: Spring-web-shop-project   File: CookiesDAO.java   View Source Code Vote up 5 votes
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 16
Project: dhus-core   File: PreAuthFilter.java   View Source Code Vote up 5 votes
private void clearCookies (HttpServletRequest request, 
   HttpServletResponse response)
{
   if (request.getCookies () != null)
   {
      for (Cookie c : request.getCookies ())
      {
         if (!"JSESSIONID".equals (c.getName ()))
         {
            c.setMaxAge (0);   
            response.addCookie (c);
         }
      }
   }
}
 
Example 17
Project: YiDu-Novel   File: CookieUtils.java   View Source Code Vote up 5 votes
/**
 * 从HTTPRequest中取出阅读履历字符串
 * 
 * @param request
 *            HttpServletRequest
 * @return 阅读履历字符串
 */
public static String getHistoryCookie(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (CookieUtils.READ_HISTORY_COOKIE.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
    }
    return null;
}
 
Example 18
Project: stage-job   File: CookieInterceptor.java   View Source Code Vote up 5 votes
@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 19
Project: xxl-job   File: CookieUtil.java   View Source Code Vote up 5 votes
/**
 * 查询Cookie
 * @param request
 * @param key
 */
private static Cookie get(HttpServletRequest request, String key) {
	Cookie[] arr_cookie = request.getCookies();
	if (arr_cookie != null && arr_cookie.length > 0) {
		for (Cookie cookie : arr_cookie) {
			if (cookie.getName().equals(key)) {
				return cookie;
			}
		}
	}
	return null;
}
 
Example 20
Project: jerrydog   File: SingleSignOn.java   View Source Code Vote up 4 votes
/**
 * Perform single-sign-on support processing for this request.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param context The valve context used to invoke the next valve
 *  in the current processing pipeline
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
public void invoke(Request request, Response response,
                   ValveContext context)
    throws IOException, ServletException {

    // If this is not an HTTP request and response, just pass them on
    if (!(request instanceof HttpRequest) ||
        !(response instanceof HttpResponse)) {
        context.invokeNext(request, response);
        return;
    }
    HttpServletRequest hreq =
        (HttpServletRequest) request.getRequest();
    HttpServletResponse hres =
        (HttpServletResponse) response.getResponse();
    request.removeNote(Constants.REQ_SSOID_NOTE);

    // Has a valid user already been authenticated?
    if (debug >= 1)
        log("Process request for '" + hreq.getRequestURI() + "'");
    if (hreq.getUserPrincipal() != null) {
        if (debug >= 1)
            log(" Principal '" + hreq.getUserPrincipal().getName() +
                "' has already been authenticated");
        context.invokeNext(request, response);
        return;
    }

    // Check for the single sign on cookie
    if (debug >= 1)
        log(" Checking for SSO cookie");
    Cookie cookie = null;
    Cookie cookies[] = hreq.getCookies();
    if (cookies == null)
        cookies = new Cookie[0];
    for (int i = 0; i < cookies.length; i++) {
        if (Constants.SINGLE_SIGN_ON_COOKIE.equals(cookies[i].getName())) {
            cookie = cookies[i];
            break;
        }
    }
    if (cookie == null) {
        if (debug >= 1)
            log(" SSO cookie is not present");
        context.invokeNext(request, response);
        return;
    }

    // Look up the cached Principal associated with this cookie value
    if (debug >= 1)
        log(" Checking for cached principal for " + cookie.getValue());
    SingleSignOnEntry entry = lookup(cookie.getValue());
    if (entry != null) {
        if (debug >= 1)
            log(" Found cached principal '" +
                entry.principal.getName() + "' with auth type '" +
                entry.authType + "'");
        request.setNote(Constants.REQ_SSOID_NOTE, cookie.getValue());
        ((HttpRequest) request).setAuthType(entry.authType);
        ((HttpRequest) request).setUserPrincipal(entry.principal);
    } else {
        if (debug >= 1)
            log(" No cached principal found, erasing SSO cookie");
        cookie.setMaxAge(0);
        hres.addCookie(cookie);
    }

    // Invoke the next Valve in our pipeline
    context.invokeNext(request, response);

}