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

The following examples show how to use javax.servlet.http.Cookie#setMaxAge() . 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: AuthServiceImpl.java    From Guns with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void logout(String token) {

    //记录退出日志
    LogManager.me().executeLog(LogTaskFactory.exitLog(LoginContextHolder.getContext().getUser().getId(), getIp()));

    //删除Auth相关cookies
    Cookie[] cookies = HttpContext.getRequest().getCookies();
    for (Cookie cookie : cookies) {
        String tokenHeader = getTokenHeaderName();
        if (tokenHeader.equalsIgnoreCase(cookie.getName())) {
            Cookie temp = new Cookie(cookie.getName(), "");
            temp.setMaxAge(0);
            HttpContext.getResponse().addCookie(temp);
        }
    }

    //删除会话
    sessionManager.removeSession(token);
}
 
Example 2
Source File: CookieUtil.java    From uccn with Apache License 2.0 6 votes vote down vote up
/**
 * 删除cookie
 *
 * @param name
 */
public static void removeCookie(String name) {
    try {

        Cookie[] cookies = getCookies();

        for (int i = 0; i < (cookies == null ? 0 : cookies.length); i++) {
            if ((name).equalsIgnoreCase(cookies[i].getName())) {

                Cookie cookie = new Cookie(name, "");
                cookie.setPath("/");
                cookie.setMaxAge(0);// 设置保存cookie最大时长为0,即使其失效
                saveCookie(cookie);
            }
        }

    } catch (Exception e) {
        System.out.println(" -------删除cookie失败!--------" + e.getMessage());
    }
}
 
Example 3
Source File: HTMLResponder.java    From charliebot with GNU General Public License v2.0 6 votes vote down vote up
private boolean makeNewCookies(HttpServletResponse httpservletresponse) {
    StringBuffer stringbuffer = new StringBuffer(17);
    StringBuffer stringbuffer1 = new StringBuffer(10);
    stringbuffer.append("webuser");
    long l = System.currentTimeMillis();
    stringbuffer.append(l);
    stringbuffer1.append(l);
    for (int j = 6; --j > 0; ) {
        int i = (int) (Math.random() * 5D);
        stringbuffer.append(i);
        stringbuffer1.append(i);
    }

    user = stringbuffer.toString();
    password = stringbuffer1.toString();
    Cookie cookie = new Cookie("alicebot_user", user);
    Cookie cookie1 = new Cookie("alicebot_password", password);
    cookie.setMaxAge(0xf4240);
    cookie1.setMaxAge(0xf4240);
    httpservletresponse.addCookie(cookie);
    httpservletresponse.addCookie(cookie1);
    return ActiveMultiplexor.getInstance().createUser(user, password, SECRET_KEY, botid);
}
 
Example 4
Source File: AuthorServlet.java    From JWT with MIT License 6 votes vote down vote up
public void doPut(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	Map<String , Object> payload=new HashMap<String, Object>();
	Date date=new Date();
	payload.put("uid", "291969452");//用户id
	payload.put("iat", date.getTime());//生成时间
	payload.put("ext",date.getTime()+1000*60*60);//过期时间1小时
	String token=null;
	token=Jwt.createToken(payload);
	
	response.setContentType("text/html;charset=UTF-8;");
	Cookie cookie=new Cookie("token", token);
	cookie.setMaxAge(3600); 
	response.addCookie(cookie);
	PrintWriter out = response.getWriter();
	out.println(token);
	out.flush();
	out.close();
}
 
Example 5
Source File: WebUtil.java    From bbs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 添加cookie
 * @param response
 * @param name cookie的名称
 * @param value cookie的值
 * @param maxAge cookie存放的时间(以秒为单位,假如存放三天,即3*24*60*60; 如果值为0,cookie将随浏览器关闭而清除)
 */
public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
	if(value != null && !"".equals(value.trim())){
		try {
			value = URLEncoder.encode(value,"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
		//	e.printStackTrace();
			if (logger.isErrorEnabled()) {
	            logger.error("添加cookie错误",e);
	        }
		}
	}
	
    Cookie cookie = new Cookie(name, value);
    cookie.setPath("/");//根目录下的所有程序都可以访问cookie
 //   cookie.setHttpOnly(true);
    if (maxAge>0) cookie.setMaxAge(maxAge);
    response.addCookie(cookie); ; 
}
 
Example 6
Source File: MiaoshaUserServiceImpl.java    From goods-seckill with Apache License 2.0 5 votes vote down vote up
private void addCookie(String token, MiaoshaUserEntity user, HttpServletResponse response) {
	redisService.set(MiaoshaUserKey.token, token, user);

	// 把token设置到cookie
	Cookie cookie = new Cookie(COOKIE_NAME_TOKEN, token);
	cookie.setMaxAge(MiaoshaUserKey.token.expireSeconds());
	cookie.setPath("/");
	response.addCookie(cookie);
}
 
Example 7
Source File: CookieUtils.java    From liteflow with Apache License 2.0 5 votes vote down vote up
/**
 * 删除cookie
 *
 * @param response      响应
 */
public static void removeUserCookie(HttpServletResponse response) {
    Cookie cookie = new Cookie(Constants.LITE_FLOW_COOKIE_NAME, null);
    cookie.setMaxAge(0);
    cookie.setPath("/");
    response.addCookie(cookie);
}
 
Example 8
Source File: ServletUtils.java    From yue-library with Apache License 2.0 5 votes vote down vote up
/**
 * 设定返回给客户端的Cookie
 * 
 * @param name cookie名
 * @param value cookie值
 * @param maxAgeInSeconds -1: 关闭浏览器清除Cookie. 0: 立即清除Cookie. &gt;0 : Cookie存在的秒数.
 * @param path Cookie的有效路径
 * @param domain the domain name within which this cookie is visible; form is according to RFC 2109
 */
public static void addCookie(String name, String value, int maxAgeInSeconds, String path, String domain) {
	Cookie cookie = new Cookie(name, value);
	if (domain != null) {
		cookie.setDomain(domain);
	}
	cookie.setMaxAge(maxAgeInSeconds);
	cookie.setPath(path);
	addCookie(cookie);
}
 
Example 9
Source File: DeleteCookies.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	Cookie cookie = null;
	Cookie[] cookies = null;
	// 获取与该域相关的 Cookie 的数组
	cookies = request.getCookies();

	// 设置响应内容类型
	response.setContentType("text/html;charset=UTF-8");

	PrintWriter out = response.getWriter();
	String title = "删除 Cookie 实例";
	String docType = "<!DOCTYPE html>\n";
	out.println(
		docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n");
	if (cookies != null) {
		out.println("<h2>Cookie 名称和值</h2>");
		for (int i = 0; i < cookies.length; i++) {
			cookie = cookies[i];
			if ((cookie.getName()).compareTo("url") == 0) {
				cookie.setMaxAge(0);
				response.addCookie(cookie);
				out.print("已删除的 cookie:" + cookie.getName() + "<br/>");
			}
			out.print("名称:" + cookie.getName() + ",");
			out.print("值:" + cookie.getValue() + " <br/>");
		}
	} else {
		out.println("<h2 class=\"tutheader\">No Cookie founds</h2>");
	}
	out.println("</body>");
	out.println("</html>");
}
 
Example 10
Source File: CookieUtil.java    From hellokoding-courses with MIT License 5 votes vote down vote up
public static void create(HttpServletResponse httpServletResponse, String name, String value, Boolean secure, Integer maxAge, String domain) {
    Cookie cookie = new Cookie(name, value);
    cookie.setSecure(secure);
    cookie.setHttpOnly(true);
    cookie.setMaxAge(maxAge);
    cookie.setDomain(domain);
    cookie.setPath("/");
    httpServletResponse.addCookie(cookie);
}
 
Example 11
Source File: AddlResponseTests_SPEC2_12_Action.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
@Override
public void processEvent(EventRequest portletReq, EventResponse portletResp) throws PortletException, IOException {

   long tid = Thread.currentThread().getId();
   portletReq.setAttribute(THREADID_ATTR, tid);

   StringWriter writer = new StringWriter();

   JSR286SpecTestCaseDetails tcd = new JSR286SpecTestCaseDetails();

   /* TestCase: V2AddlResponseTests_SPEC2_12_Action_cookie3 */
   /* Details: "Cookies set during the Action phase should be available */
   /* to the portlet during the Event phase" */
   if (portletReq.getParameter("tr2") != null && portletReq.getParameter("tr2").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 tr2 = tcd.getTestResultFailed(V2ADDLRESPONSETESTS_SPEC2_12_ACTION_COOKIE3);
      for (Cookie c : cookies) {
         txt.append("Name: ").append(c.getName());
         txt.append(", Value: ").append(c.getValue()).append("<br>");
         if (c.getName().equals("action_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());
   }
   portletReq.getPortletSession().setAttribute(RESULT_ATTR_PREFIX + "AddlResponseTests_SPEC2_12_Action_event", writer.toString(), APPLICATION_SCOPE);
}
 
Example 12
Source File: UserService.java    From game-server with MIT License 5 votes vote down vote up
/**
	 * 存储 cookie
	 * 
	 * @param session
	 * @param muser
	 * @param response
	 */
	public void saveCookie(HttpSession session, String userName, HttpServletResponse response) {
		Cookie sessionCookie = new Cookie(SessionKey.HTTP_SESSION, session.getId());
		sessionCookie.setMaxAge(3600);
		sessionCookie.setPath("/");
		response.addCookie(sessionCookie);
		
//		session.setAttribute(SessionKey.USER_NAME, userName);
		Cookie loginidCookie = new Cookie(SessionKey.USER_NAME, userName);
		// 30*24*60*60
		loginidCookie.setMaxAge(2592000);
		loginidCookie.setPath("/");
		response.addCookie(loginidCookie);
	}
 
Example 13
Source File: CookieUtil.java    From two-token-sw with Apache License 2.0 5 votes vote down vote up
public static void refreshSessionCookie(HttpServletRequest request, HttpServletResponse response,
    String cookieName, String domain, int maxAge) {
  Cookie cookie = getSessionCookie(request, cookieName);
  if (cookie != null) {
    cookie.setMaxAge(maxAge);
    cookie.setDomain(domain);
    cookie.setPath("/");
    response.addCookie(cookie);
  }
}
 
Example 14
Source File: JWTUtil.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
/**
 * Send JWT log off response.
 *
 * @param response     response to render
 *
 * @throws IOException error
 */
static void sendLogOffJWT(final HttpServletResponse response) throws IOException {

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");

    final Cookie xAuth = new Cookie(JWTUtil.COOKIE_HEADER, "");
    xAuth.setMaxAge(0);
    xAuth.setVersion(1);
    response.addCookie(xAuth);

    response.getWriter().write("{\"token\": null }");

}
 
Example 15
Source File: LogoutServlet.java    From opensoc-streaming with Apache License 2.0 5 votes vote down vote up
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 
{
	logger.info( "Doing logout here..." );
	
	Subject currentUser = SecurityUtils.getSubject();

	currentUser.logout();
	
	Cookie authCookie = new Cookie("authToken", "Logout" );
	authCookie.setMaxAge( 0 );
	resp.addCookie(authCookie);
	
	resp.sendRedirect( "/login.jsp" );
}
 
Example 16
Source File: WebUtils.java    From xmanager with Apache License 2.0 5 votes vote down vote up
/**
 * 设置cookie
 * @param response
 * @param name
 * @param value
 * @param maxAgeInSeconds
 */
public static void setCookie(HttpServletResponse response, String name, String value, int maxAgeInSeconds) {
	Cookie cookie = new Cookie(name, value);
	cookie.setPath("/");
	cookie.setMaxAge(maxAgeInSeconds);
	cookie.setHttpOnly(true);
	response.addCookie(cookie);
}
 
Example 17
Source File: CookieHelper.java    From kisso with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * 添加 Cookie
 * </p>
 *
 * @param response
 * @param domain   所在域
 * @param path     域名路径
 * @param name     名称
 * @param value    内容
 * @param maxAge   生命周期参数
 * @param httpOnly 只读
 * @param secured  Https协议下安全传输
 */
public static void addCookie(HttpServletResponse response, String domain, String path, String name, String value,
                             int maxAge, boolean httpOnly, boolean secured) {
    Cookie cookie = new Cookie(name, value);
    /**
     * 不设置该参数默认 当前所在域
     */
    if (StringUtils.isNotEmpty(domain)) {
        cookie.setDomain(domain);
    }
    cookie.setPath(path);
    cookie.setMaxAge(maxAge);

    /** Cookie 只在Https协议下传输设置 */
    if (secured) {
        cookie.setSecure(secured);
    }

    /** Cookie 只读设置 */
    if (httpOnly) {
        addHttpOnlyCookie(response, cookie);
    } else {
        /**
         * servlet 3.0 support
         * cookie.setHttpOnly(httpOnly)
         */
        response.addCookie(cookie);
    }
}
 
Example 18
Source File: Servlets.java    From howsun-javaee-framework with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param response
 * @param name
 * @param value
 * @param domain
 * @param expiry 有效期(秒)
 * @param uri
 */
public static void setCookieValue(HttpServletResponse response, String name, String value, String domain, Integer expiry, String uri){
	Cookie cookie = new Cookie(name, value);
	if(domain != null){
		cookie.setDomain(domain);
	}
	if(expiry != null){
		cookie.setMaxAge(expiry);
	}
	if(uri != null){
		cookie.setPath(uri);
	}
	response.addCookie(cookie);
}
 
Example 19
Source File: Sessions.java    From symphonyx with Apache License 2.0 4 votes vote down vote up
/**
 * Logouts a user with the specified request.
 *
 * @param request the specified request
 * @param response the specified response
 * @return {@code true} if succeed, otherwise returns {@code false}
 */
public static boolean logout(final HttpServletRequest request, final HttpServletResponse response) {
    final HttpSession session = request.getSession(false);

    if (null != session) {
        final Cookie cookie = new Cookie("b3log-latke", null);

        cookie.setMaxAge(0);
        cookie.setPath("/");

        response.addCookie(cookie);

        session.invalidate();

        return true;
    }

    return false;
}
 
Example 20
Source File: CookieUtil.java    From JavaWeb with Apache License 2.0 4 votes vote down vote up
public static void setCookie(String key,String value,HttpServletResponse response){
	Cookie c = new Cookie(key, value);
	c.setMaxAge(ConstantUtil.COOKIE_MAXAGE);
	c.setPath(ConstantUtil.COOKIE_PATH);
	response.addCookie(c);
}