javax.servlet.http.Cookie#setValue()源码实例Demo

下面列出了javax.servlet.http.Cookie#setValue() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: zrlog   文件: AdminPageController.java
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);
}
 
源代码2 项目: projectforge-webapp   文件: LoginPage.java
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);
  }
}
 
@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);
}
 
源代码4 项目: bamboobsc   文件: UserCurrentCookie.java
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();
	}					
}
 
源代码5 项目: my-site   文件: AuthController.java
/**
 * 注销
 *
 * @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);
    }
}
 
@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");
            }
         }
      }
   }
}
 
@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;
}
 
源代码8 项目: keeper   文件: SessionSubject.java
@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 + "");

}
 
源代码9 项目: web-flash   文件: WafRequestWrapper.java
/**
 * @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;
}
 
源代码10 项目: Roothub   文件: CookieAndSessionUtil.java
/**
 * 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);
			}
		}
	}
}
 
源代码11 项目: ICERest   文件: HttpResponse.java
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;
}
 
源代码12 项目: open-cloud   文件: WebUtils.java
/**
 * 设置 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);
}
 
源代码13 项目: sdudoc   文件: CookieUtil.java
/** 删除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;
}
 
源代码14 项目: Shop-for-JavaWeb   文件: CookieUtils.java
/**
 * 设置 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);
}
 
源代码15 项目: onedev   文件: ServletWebResponse.java
@Override
public void clearCookie(Cookie cookie)
{
	cookie.setMaxAge(0);
	cookie.setValue(null);
	addCookie(cookie);
}
 
@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");

}
 
@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");
  }

}
 
源代码18 项目: cuba   文件: CubaApplicationServlet.java
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());
}
 
源代码19 项目: Tomcat7.0.67   文件: SingleSignOn.java
/**
 * 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);
}
 
源代码20 项目: super-cloudops   文件: CookieUtils.java
/**
 * 设置 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);
}