Java Code Examples for javax.servlet.http.Cookie#setValue()

The following examples show how to use javax.servlet.http.Cookie#setValue() . 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: AdminPageController.java    From zrlog with Apache License 2.0 6 votes vote down vote up
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 2
Source File: AuthController.java    From my-site with Apache License 2.0 6 votes vote down vote up
/**
 * 注销
 *
 * @param session
 * @param response
 */
@RequestMapping("/logout")
public void logout(HttpSession session, HttpServletResponse response, org.apache.catalina.servlet4preview.http.HttpServletRequest request) {
    session.removeAttribute(WebConst.LOGIN_SESSION_KEY);
    Cookie cookie = new Cookie(WebConst.USER_IN_COOKIE, "");
    cookie.setValue(null);
    cookie.setMaxAge(0);// 立即销毁cookie
    cookie.setPath("/");
    response.addCookie(cookie);
    try {
        response.sendRedirect("/admin/login");
    } catch (IOException e) {
        e.printStackTrace();
        LOGGER.error("注销失败", e);
    }
}
 
Example 3
Source File: LoginPage.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
public static void logout(final MySession mySession, final HttpServletRequest request, final HttpServletResponse response,
    final UserXmlPreferencesCache userXmlPreferencesCache, final MenuBuilder menuBuilder)
{
  final PFUserDO user = mySession.getUser();
  if (user != null) {
    userXmlPreferencesCache.flushToDB(user.getId());
    userXmlPreferencesCache.clear(user.getId());
    if (menuBuilder != null) {
      menuBuilder.expireMenu(user.getId());
    }
  }
  mySession.logout();
  final Cookie stayLoggedInCookie = UserFilter.getStayLoggedInCookie(request);
  if (stayLoggedInCookie != null) {
    stayLoggedInCookie.setMaxAge(0);
    stayLoggedInCookie.setValue(null);
    stayLoggedInCookie.setPath("/");
    response.addCookie(stayLoggedInCookie);
  }
}
 
Example 4
Source File: CookieSessionTracking.java    From HttpSessionReplacer with MIT License 6 votes vote down vote up
@Override
public void propagateSession(RequestWithSession request, Object response) {
  Cookie cookie = new Cookie(idName, "");
  RepositoryBackedSession session = request.getRepositoryBackedSession(false);
  if (session != null && !session.isValid()) {
    session = null;
  }
  if (session == null) {
    cookie.setMaxAge(0);
  } else {
    cookie.setValue(session.getId());
  }
  if (ServletLevel.isServlet3) {
    cookie.setHttpOnly(httpOnly);
  }
  HttpServletRequest httpRequest = (HttpServletRequest)request;
  if (secure) {
    cookie.setSecure(secureOnlyOnSecuredRequest ? httpRequest.isSecure() : true);
  }
  cookie.setPath(cookiePath());
  ((HttpServletResponse)response).addCookie(cookie);
}
 
Example 5
Source File: UserCurrentCookie.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
public static void setCurrentId(HttpServletResponse response, String currentId, String sessionId, 
		String account, String language) {
	try {
		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); // 2018-07-04 rem
		cookie.setHttpOnly(false); // 2018-07-04 add
		response.addCookie(cookie);				
	} catch (Exception e) {
		e.printStackTrace();
	}					
}
 
Example 6
Source File: HeaderPortletTests_SPEC15_Header.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
@Override
public void processAction(ActionRequest actionRequest,
      ActionResponse actionResponse) throws PortletException, IOException {
   String action = actionRequest.getParameter("inputval");
   if (action != null) {
      if (V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS10.equals(action)
            && actionRequest.getParameter("actionURLTr0") != null
            && actionRequest.getParameter("actionURLTr0").equals("true")) {
         /* TestCase: V2AddlRequestTests_SPEC2_11_Render_parameters10 */
         /* Details: "The portlet-container must not propagate parameters */
         /* received in an action or event request to subsequent render */
         /* requests of the portlet" */
         actionResponse.setRenderParameter("tr0", "true");
      } else if (V3HEADERPORTLETTESTS_SPEC15_HEADER_PARAMETERS15
            .equals(action) && actionRequest.getParameter("tr3a") != null
            && actionRequest.getParameter("tr3a").equals("true")) {
         /* TestCase: V3HeaderPortletTests_SPEC15_Header_parameters15 */
         /*
          * Details: "Render parameters get automatically cleared if the
          * portlet receives a processAction or processEvent call"
          */
         actionResponse.setRenderParameter("tr3b", "true");
      } else if (V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE9.equals(action)) {
         /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie9 */
         /*
          * Details: "Cookies set during the Header phase should be available
          * to the portlet during a subsequent Action phase"
          */
         Cookie[] cookies = actionRequest.getCookies();
         for (Cookie c : cookies) {
            if (c.getName().equals("header_tr1_cookie")
                  && c.getValue().equals("true")) {
               c.setMaxAge(0);
               c.setValue("");
               actionResponse.setRenderParameter("trCookie1", "true");
            }
         }
      }
   }
}
 
Example 7
Source File: ServletWebResponse.java    From onedev with MIT License 5 votes vote down vote up
@Override
public void clearCookie(Cookie cookie)
{
	cookie.setMaxAge(0);
	cookie.setValue(null);
	addCookie(cookie);
}
 
Example 8
Source File: CookieUtils.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
/**
 * 设置 Cookie
 * @param name 名称
 * @param value 值
 * @param maxAge 生存时间(单位秒)
 * @param uri 路径
 */
public static void setCookie(HttpServletResponse response, String name, String value, String path, int maxAge) {
	Cookie cookie = new Cookie(name, null);
	cookie.setPath(path);
	cookie.setMaxAge(maxAge);
	try {
		cookie.setValue(URLEncoder.encode(value, "utf-8"));
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}
	response.addCookie(cookie);
}
 
Example 9
Source File: CookieUtil.java    From sdudoc with MIT License 5 votes vote down vote up
/** 删除cookie */
public Cookie delCookie(HttpServletRequest request, String cookieName) {
	Cookie[] cookies = request.getCookies();
	if (cookies != null) {
		for (Cookie cookie : cookies) {
			if (cookieName.equals(cookie.getName())) {
				cookie.setValue("");
				cookie.setPath("/");
				cookie.setMaxAge(0);
				return cookie;
			}
		}
	}
	return null;
}
 
Example 10
Source File: WebUtils.java    From open-cloud with MIT License 5 votes vote down vote up
/**
 * 设置 Cookie
 *
 * @param name   名称
 * @param value  值
 * @param maxAge 生存时间(单位秒)
 * @param path   路径
 */
public static void setCookie(HttpServletResponse response, String name, String value, String path, int maxAge) {
    Cookie cookie = new Cookie(name, null);
    cookie.setPath(path);
    cookie.setMaxAge(maxAge);
    try {
        cookie.setValue(URLEncoder.encode(value, "utf-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    response.addCookie(cookie);
}
 
Example 11
Source File: HttpResponse.java    From ICERest with Apache License 2.0 5 votes vote down vote up
public Response clearCookie(String cookie) {
    Cookie existingCookie = HttpRequest.getCookie(request.getCookies(), cookie);
    if (existingCookie != null) {
        existingCookie.setPath("/");
        existingCookie.setValue("");
        existingCookie.setMaxAge(0);
        response.addCookie(existingCookie);
    }
    return this;
}
 
Example 12
Source File: CookieAndSessionUtil.java    From Roothub with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * editCookie
 * @param request
 * @param cookieName
 * @param cookieValue
 */
public static void editCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
							  String cookieValue) {
	Cookie[] cookies = request.getCookies();
	if (cookies != null) {
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals(cookieName)) {
				cookie.setValue(cookieValue);
				response.addCookie(cookie);
			}
		}
	}
}
 
Example 13
Source File: WafRequestWrapper.java    From web-flash with MIT License 5 votes vote down vote up
/**
 * @Description Cookie内容过滤
 * @return
 */
@Override
public Cookie[] getCookies() {
	Cookie[] existingCookies = super.getCookies();
	if (existingCookies != null) {
		for (int i = 0 ; i < existingCookies.length ; ++i) {
			Cookie cookie = existingCookies[i];
			cookie.setValue(filterParamString(cookie.getValue()));
		}
	}
	return existingCookies;
}
 
Example 14
Source File: SessionSubject.java    From keeper with Apache License 2.0 5 votes vote down vote up
@Override
public void logout() {
    HttpSession session = WebUtil.currentSession();
    if (null == session) {
        return;
    }
    session.removeAttribute(KEEPER_SESSION_KEY);

    HttpServletResponse response = WebUtil.currentResponse();

    Cookie cookie = getRenewCookie();
    if (null == cookie) {
        return;
    }
    String token = cookie.getValue();
    cookie.setValue("");
    cookie.setMaxAge(-1);
    response.addCookie(cookie);

    String username = getUsername(token);
    if (StringUtil.isEmpty(username)) {
        return;
    }

    // 修改当前 token 的过期时间
    String loginTokenKey = String.format(KEEPER_LOGIN_KEY, username, token.substring(token.lastIndexOf(".") + 1));
    keeperCache().set(loginTokenKey, System.currentTimeMillis() / 1000 + "");

}
 
Example 15
Source File: XssSqlHttpServletRequestWrapper.java    From bootshiro with MIT License 5 votes vote down vote up
@Override
public Cookie[] getCookies() {
    Cookie[] cookies = super.getCookies();
    if (cookies != null) {
        for (int i = 0 ; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            cookie.setValue(filterParamString(cookie.getValue()));
        }
    }
    return cookies;
}
 
Example 16
Source File: AddlResponseTests_SPEC2_12_Event_event.java    From portals-pluto with Apache License 2.0 4 votes vote down vote up
@Override
public void render(RenderRequest portletReq, RenderResponse portletResp)
    throws PortletException, IOException {

  JSR286SpecTestCaseDetails tcd = new JSR286SpecTestCaseDetails();

  portletResp.setContentType("text/html");
  PrintWriter writer = portletResp.getWriter();
  writer.write("<h3>Event Companion Portlet </h3>\n");
  writer.write("<p>AddlResponseTests_SPEC2_12_Event_event</p>\n");

  String msg = (String) portletReq.getPortletSession()
      .getAttribute(RESULT_ATTR_PREFIX + "AddlResponseTests_SPEC2_12_Event", APPLICATION_SCOPE);
  msg = (msg == null) ? "Not ready. click test case link." : msg;
  writer.write("<p>" + msg + "</p>\n");

  if (portletReq.getParameter("tr0") != null && portletReq.getParameter("tr0").equals("true")) {
    Cookie[] cookies = portletReq.getCookies();

    StringBuilder txt = new StringBuilder(128);
    txt.append("<p>Debug info:");
    txt.append("<br>");

    txt.append("# Cookies: ").append(cookies.length).append("<br>");
    TestResult tr0 = tcd.getTestResultFailed(V2ADDLRESPONSETESTS_SPEC2_12_EVENT_COOKIE5);
    for (Cookie c : cookies) {
      txt.append("Name: ").append(c.getName());
      txt.append(", Value: ").append(c.getValue()).append("<br>");
      if (c.getName().equals("event_tr0_cookie") && c.getValue().equals("true")) {
        txt.append("<br>").append("Found my cookie!").append("<br>");
        c.setMaxAge(0);
        c.setValue("");
        tr0.setTcSuccess(true);
      }
    }
    tr0.writeTo(writer);
    txt.append("</p>");
    writer.append(txt.toString());
  }

  if (portletReq.getParameter("tr1") != null && portletReq.getParameter("tr1").equals("true")) {
    writer.write("<div id=\"AddlResponseTests_SPEC2_11_Event\">no resource output.</div>\n");
    ResourceURL resurl = portletResp.createResourceURL();
    resurl.setCacheability(PAGE);
    writer.write("<script>\n");
    writer.write("(function () {\n");
    writer.write("   var xhr = new XMLHttpRequest();\n");
    writer.write("   xhr.onreadystatechange=function() {\n");
    writer.write("      if (xhr.readyState==4 && xhr.status==200) {\n");
    writer.write(
        "         document.getElementById(\"AddlResponseTests_SPEC2_11_Event\").innerHTML=xhr.responseText;\n");
    writer.write("      }\n");
    writer.write("   };\n");
    writer.write("   xhr.open(\"GET\",\"" + resurl.toString() + "\",true);\n");
    writer.write("   xhr.send();\n");
    writer.write("})();\n");
    writer.write("</script>\n");
  }

}
 
Example 17
Source File: HeaderPortletTests_SPEC15_Header.java    From portals-pluto with Apache License 2.0 4 votes vote down vote up
@Override
public void render(RenderRequest renderRequest, RenderResponse renderResponse)
      throws PortletException, IOException {

   ModuleTestCaseDetails tcd = new ModuleTestCaseDetails();

   PrintWriter writer = renderResponse.getWriter();

   /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie8 */
   /*
    * Details: "Cookies set during the Header phase should be available to
    * the portlet during the Resource phase"
    */
   writer.write(
         "<div id=\"V3HeaderPortletTests_SPEC15_Header\">no resource output.</div>\n");
   ResourceURL resurl = renderResponse.createResourceURL();
   resurl.setCacheability(PAGE);
   writer.write("<script>\n");
   writer.write("(function () {\n");
   writer.write("   var xhr = new XMLHttpRequest();\n");
   writer.write("   xhr.onreadystatechange=function() {\n");
   writer.write("      if (xhr.readyState==4 && xhr.status==200) {\n");
   writer.write(
         "         document.getElementById(\"V3HeaderPortletTests_SPEC15_Header\").innerHTML=xhr.responseText;\n");
   writer.write("      }\n");
   writer.write("   };\n");
   writer.write(
         "   xhr.open(\"GET\",\"" + resurl.toString() + "\",true);\n");
   writer.write("   xhr.send();\n");
   writer.write("})();\n");
   writer.write("</script>\n");

   /* TestCase: V3HeaderPortletTests_SPEC15_Header_cookie10 */
   /*
    * Details: "Cookies set during the Header phase should be available to
    * the portlet during a subsequent Render phase"
    */
   Cookie[] cookies = renderRequest.getCookies();
   StringBuilder txt = new StringBuilder(128);
   txt.append("<p>Debug info:");
   txt.append("<br>");
   txt.append("# Cookies: ").append(cookies.length).append("<br>");
   TestResult tr2 = tcd
         .getTestResultFailed(V3HEADERPORTLETTESTS_SPEC15_HEADER_COOKIE10);
   for (Cookie c : cookies) {
      txt.append("Name: ").append(c.getName());
      txt.append(", Value: ").append(c.getValue()).append("<br>");
      if (c.getName().equals("header_tr2_cookie")
            && c.getValue().equals("true")) {
         txt.append("<br>").append("Found my cookie!").append("<br>");
         c.setMaxAge(0);
         c.setValue("");
         tr2.setTcSuccess(true);
      }
   }
   tr2.writeTo(writer);
   txt.append("</p>");
   writer.append(txt.toString());

   String msg = (String) renderRequest.getAttribute(
         RESULT_ATTR_PREFIX + "HeaderPortletTests_SPEC15_Header");
   writer.write("<p>" + msg + "</p>");
   renderRequest.removeAttribute(
         RESULT_ATTR_PREFIX + "HeaderPortletTests_SPEC15_Header");

}
 
Example 18
Source File: CubaApplicationServlet.java    From cuba with Apache License 2.0 4 votes vote down vote up
protected void redirectToApp(HttpServletRequest request, HttpServletResponse response,
                             String contextName, String[] uriParts, String action) throws IOException {
    StringBuilder redirectAddress = new StringBuilder();
    for (int i = 0; i < uriParts.length; i++) {
        redirectAddress.append(uriParts[i]);
        if (uriParts[i].equals(contextName)) {
            break;
        }
        if (i < uriParts.length - 1) {
            redirectAddress.append("/");
        }
    }

    // redirect to ROOT context
    if (redirectAddress.length() == 0) {
        redirectAddress.append("/");
    }

    HttpSession httpSession = request.getSession();
    if (action != null) {
        httpSession.setAttribute(AppUI.LAST_REQUEST_ACTION_ATTR, action);
    }
    if (request.getParameterNames().hasMoreElements()) {
        Map<String, String> params = new HashMap<>();
        Enumeration parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String name = (String) parameterNames.nextElement();
            if (!FROM_HTML_REDIRECT_PARAM.equals(name)) {
                params.put(name, request.getParameter(name));
            }
        }
        httpSession.setAttribute(AppUI.LAST_REQUEST_PARAMS_ATTR, params);
    }

    statisticsCounter.incWebRequestsCount();
    String httpSessionId = httpSession.getId();
    log.debug("Redirect to application {}", httpSessionId);

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if ("JSESSIONID".equals(cookie.getName()) && !httpSessionId.equals(cookie.getValue())) {
                cookie.setValue(httpSessionId);
                break;
            }
        }
    }
    response.sendRedirect(redirectAddress.toString());
}
 
Example 19
Source File: SingleSignOn.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * 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
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
@Override
public void invoke(Request request, Response response)
    throws IOException, ServletException {

    request.removeNote(Constants.REQ_SSOID_NOTE);

    // Has a valid user already been authenticated?
    if (containerLog.isDebugEnabled()) {
        containerLog.debug(sm.getString("singleSignOn.debug.invoke", request.getRequestURI()));
    }
    if (request.getUserPrincipal() != null) {
        if (containerLog.isDebugEnabled()) {
            containerLog.debug(sm.getString("singleSignOn.debug.hasPrincipal",
                    request.getUserPrincipal().getName()));
        }
        getNext().invoke(request, response);
        return;
    }

    // Check for the single sign on cookie
    if (containerLog.isDebugEnabled()) {
        containerLog.debug(sm.getString("singleSignOn.debug.cookieCheck"));
    }
    Cookie cookie = null;
    Cookie cookies[] = request.getCookies();
    if (cookies != null) {
        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 (containerLog.isDebugEnabled()) {
            containerLog.debug(sm.getString("singleSignOn.debug.cookieNotFound"));
        }
        getNext().invoke(request, response);
        return;
    }

    // Look up the cached Principal associated with this cookie value
    if (containerLog.isDebugEnabled()) {
        containerLog.debug(sm.getString("singleSignOn.debug.principalCheck",
                cookie.getValue()));
    }
    SingleSignOnEntry entry = cache.get(cookie.getValue());
    if (entry != null) {
        if (containerLog.isDebugEnabled()) {
            containerLog.debug(sm.getString("singleSignOn.debug.principalFound",
                    entry.getPrincipal() != null ? entry.getPrincipal().getName() : "",
                    entry.getAuthType()));
        }
        request.setNote(Constants.REQ_SSOID_NOTE, cookie.getValue());
        // Only set security elements if reauthentication is not required
        if (!getRequireReauthentication()) {
            request.setAuthType(entry.getAuthType());
            request.setUserPrincipal(entry.getPrincipal());
        }
    } else {
        if (containerLog.isDebugEnabled()) {
            containerLog.debug(sm.getString("singleSignOn.debug.principalNotFound",
                    cookie.getValue()));
        }
        // No need to return a valid SSO session ID
        cookie.setValue("REMOVE");
        // Age of zero will trigger removal
        cookie.setMaxAge(0);
        // Domain and path have to match the original cookie to 'replace'
        // the original cookie
        cookie.setPath("/");
        String domain = getCookieDomain();
        if (domain != null) {
            cookie.setDomain(domain);
        }
        // This is going to trigger a Set-Cookie header. While the value is
        // not security sensitive, ensure that expectations for secure and
        // httpOnly are met
        cookie.setSecure(request.isSecure());
        if (request.getServletContext().getSessionCookieConfig().isHttpOnly() ||
                request.getContext().getUseHttpOnly()) {
            cookie.setHttpOnly(true);
        }

        response.addCookie(cookie);
    }

    // Invoke the next Valve in our pipeline
    getNext().invoke(request, response);
}
 
Example 20
Source File: CookieUtils.java    From super-cloudops with Apache License 2.0 3 votes vote down vote up
/**
 * 设置 Cookie
 * 
 * @param name
 *            名称
 * @param value
 *            值
 * @param maxAge
 *            生存时间(单位秒)
 * @param uri
 *            路径
 */
public static void setCookie(HttpServletResponse response, String name, String value, String path, int maxAge) {
	Cookie cookie = new Cookie(name, null);
	cookie.setPath(path);
	cookie.setMaxAge(maxAge);
	try {
		cookie.setValue(URLEncoder.encode(value, "utf-8"));
	} catch (UnsupportedEncodingException e) {
		throw new IllegalStateException(e);
	}
	response.addCookie(cookie);
}