下面列出了javax.servlet.http.Cookie#setMaxAge() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
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);
}
/**
* 添加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); ;
}
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();
}
/**
* 删除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());
}
}
/**
* 删除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);
}
/**
*
* @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);
}
/**
* <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);
}
}
/**
* 设置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);
}
@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" );
}
/**
* 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 }");
}
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);
}
}
/**
* 存储 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);
}
@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);
}
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);
}
/**
* @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>");
}
/**
* 设定返回给客户端的Cookie
*
* @param name cookie名
* @param value cookie值
* @param maxAgeInSeconds -1: 关闭浏览器清除Cookie. 0: 立即清除Cookie. >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);
}
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);
}
/**
* 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;
}
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);
}