Example usage for javax.servlet.http Cookie Cookie

List of usage examples for javax.servlet.http Cookie Cookie

Introduction

In this page you can find the example usage for javax.servlet.http Cookie Cookie.

Prototype

public Cookie(String name, String value) 

Source Link

Document

Constructs a cookie with the specified name and value.

Usage

From source file:io.gravitee.management.security.JWTCookieGenerator.java

public Cookie generate(final String value) {
    final Cookie cookie = new Cookie(HttpHeaders.AUTHORIZATION, value);
    cookie.setHttpOnly(true);/*www . j  av  a 2 s.c o  m*/
    cookie.setSecure(environment.getProperty("jwt.cookie-secure", Boolean.class, DEFAULT_JWT_COOKIE_SECURE));
    cookie.setPath(environment.getProperty("jwt.cookie-path", DEFAULT_JWT_COOKIE_PATH));
    cookie.setDomain(environment.getProperty("jwt.cookie-domain", DEFAULT_JWT_COOKIE_DOMAIN));
    return cookie;
}

From source file:spring.travel.site.controllers.LogoutController.java

@RequestMapping(method = RequestMethod.GET)
public View logout(HttpServletResponse response) {
    Cookie cookie = new Cookie(cookieName, "");
    cookie.setMaxAge(0);/* www  . ja  v a  2  s .c o m*/
    response.addCookie(cookie);
    return new RedirectView("/");
}

From source file:com.woonoz.proxy.servlet.CookieFormatterTest.java

@Test
public void testJSessionIdCookie() throws InvalidCookieException {
    String sessionId = "JJJ2234312421";
    Cookie cookie = new Cookie("JSESSIONID", sessionId);
    cookie.setPath("/");
    CookieFormatter formatter = CookieFormatter.createFromServletCookie(cookie);
    Assert.assertEquals("JSESSIONID=JJJ2234312421; path=/;", formatter.asString());
}

From source file:MyServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    Cookie cookie = null;//from   w  ww  . j av  a  2 s.c om
    //Get an array of Cookies associated with this domain
    Cookie[] cookies = request.getCookies();
    boolean newCookie = false;

    //Get the 'mycookie' Cookie if it exists
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("mycookie")) {
                cookie = cookies[i];
            }
        } //end for
    } //end if

    if (cookie == null) {
        newCookie = true;
        //Get the cookie's Max-Age from a context-param element
        //If the 'cookie-age' param is not set properly
        //then set the cookie to a default of -1, 'never expires'
        int maxAge;
        try {
            maxAge = new Integer(getServletContext().getInitParameter("cookie-age")).intValue();
        } catch (Exception e) {
            maxAge = -1;
        }

        //Create the Cookie object

        cookie = new Cookie("mycookie", "" + getNextCookieValue());
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);

    } //end if
      // get some info about the cookie
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Cookie info</title>");
    out.println("</head>");
    out.println("<body>");

    out.println("<h2> Information about the cookie named \"mycookie\"</h2>");

    out.println("Cookie value: " + cookie.getValue() + "<br>");
    if (newCookie) {
        out.println("Cookie Max-Age: " + cookie.getMaxAge() + "<br>");
        out.println("Cookie Path: " + cookie.getPath() + "<br>");
    }

    out.println("</body>");
    out.println("</html>");

    out.close();
}

From source file:com.ms.commons.summer.security.web.DefaultSecurityFormResolver.java

/**
 * ?tokenCookie//from w ww  .  j  a v  a  2 s  . co  m
 * 
 * @param request
 * @param str
 */
public void renderSessionTokenInput(final HttpServletRequest request, final HttpServletResponse response,
        final StringBuilder str) {
    String token = createToken();
    Cookie cookie = new Cookie(FORM_RESUBMIT_TOKEN, token);
    cookie.setPath("/");
    response.addCookie(cookie);
    str.append("<input type=\"hidden\" name=\"").append(FORM_RESUBMIT_TOKEN).append("\" value=\"").append(token)
            .append("\"/>");
    if (logger.isDebugEnabled()) {
        logger.debug("render session token value = " + token);
    }
}

From source file:com.nkapps.billing.services.SearchServiceImpl.java

@Override
public String execSearchBy(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Cookie sbtCookie = null;//from w w w.  ja v  a  2 s.  c  o m

    String searchBy = request.getParameter("searchBy");
    if (searchBy == null) {
        Cookie[] requestCookies = request.getCookies();
        for (Cookie c : requestCookies) {
            if (c.getName().equals("searchBy")) {
                sbtCookie = c;
            }
        }
        if (sbtCookie != null) {
            searchBy = URLDecoder.decode(sbtCookie.getValue(), "UTF-8");
        } else {
            searchBy = "";
        }
    } else {
        sbtCookie = new Cookie("searchBy", URLEncoder.encode(searchBy, "UTF-8"));
        sbtCookie.setPath("/");
        response.addCookie(sbtCookie);
    }
    return searchBy;
}

From source file:com.netsteadfast.greenstep.base.sys.UserCurrentCookie.java

public static void setCurrentId(HttpServletResponse response, String currentId, String sessionId,
        String account, String language) {
    try {/*from   w  w w  .  j ava 2s .  c o  m*/
        String value = currentId + Constants.ID_DELIMITER + sessionId + Constants.ID_DELIMITER + account
                + Constants.ID_DELIMITER + language;
        String encValue = EncryptorUtils.encrypt(Constants.getEncryptorKey1(), Constants.getEncryptorKey2(),
                value);
        encValue = SimpleUtils.toHex(encValue);
        Cookie cookie = new Cookie(Constants.APP_SITE_CURRENTID_COOKIE_NAME, encValue);
        cookie.setPath("/");
        cookie.setValue(encValue);
        cookie.setMaxAge(60 * 60 * 24); // 1-day
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.shareok.data.webserv.HomeController.java

@RequestMapping("/home")
public ModelAndView home(HttpServletRequest req, HttpServletResponse res) {

    ModelAndView model = new ModelAndView();
    model.setViewName("home");
    HttpSession session = (HttpSession) req.getSession(false);
    if (null != session) {
        RedisUser user = (RedisUser) session
                .getAttribute(ShareokdataManager.getSessionRedisUserAttributeName());
        if (null != user) {
            Cookie userCookie = new Cookie("userId", String.valueOf(user.getUserId()));
            userCookie.setMaxAge(30 * 60);
            res.addCookie(userCookie);/*from w ww . ja  va2  s.  c o m*/
            model.addObject("user", user);
            model.addObject("loginTime", session.getCreationTime());
        }
    }
    return model;
}

From source file:com.usefullc.platform.common.utils.CookieUtils.java

/**
 * cookie//from  w w  w.  j  av  a 2s .  c o m
 * 
 * @param response
 * @param name
 * @param value
 * @param domain
 * @param expire
 */
public static void addCookie(HttpServletResponse response, String name, String value, String domain,
        Integer expire) {
    Cookie cookie = new Cookie(name, value);
    if (StringUtils.isNotEmpty(domain)) {
        cookie.setDomain(domain);
    }
    if (expire != null) {
        cookie.setMaxAge(expire);
    }
    cookie.setPath("/");
    response.addCookie(cookie);
}

From source file:com.ar.dev.tierra.api.config.CsrfHeaderFilter.java

/**
 * Metodo para agregar cookie contra CRSF
 * @param request//from   w  ww .jav  a2  s .co  m
 * @param response
 * @param filterChain
 * @throws ServletException
 * @throws IOException 
 */
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
    if (csrf != null) {
        Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
        String token = csrf.getToken();
        if (cookie == null || token != null && !token.equals(cookie.getValue())) {
            cookie = new Cookie("XSRF-TOKEN", token);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
    }
    filterChain.doFilter(request, response);
}