com.github.jackpanz.spring.util.CookieHelper Maven / Gradle / Ivy
The newest version!
package com.github.jackpanz.spring.util;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Created by Administrator on 2016/5/31.
*/
public class CookieHelper {
public static void main(String[] args) {
String sb1 = "com.dordor.coupon.mapper.CouponMapper.BaseResultMap";
String sb2 = "com.dordor.coupon.entity.Coupon";
sb1 = sb1.substring(0,sb1.lastIndexOf("."));
System.out.println("".getClass().getPackage().getName());
System.out.println(sb1.substring(0,sb1.lastIndexOf(".")));
System.out.println(sb2.substring(0,sb2.lastIndexOf(".")));
}
// 清除cookie總保存的所有信息
public static void clearAllCookie(HttpServletRequest servletRequest, HttpServletResponse res)
{
Cookie[] cookies = servletRequest.getCookies();
try
{
for(Cookie cookie:cookies)
{
cookie.setValue( null);
cookie.setPath("/");
cookie.setMaxAge(0);
res.addCookie(cookie);
}
}catch(Exception ex)
{
ex.printStackTrace();
}
}
// 根據cookie的名稱清除cookie
public static void clearCookieByCookieName(HttpServletRequest servletRequest, HttpServletResponse res,String cookieName)
{
try
{
Cookie[] cookies = servletRequest.getCookies();
if(null != cookies)
{
for(Cookie cookie:cookies)
{
if(cookieName.equals(cookie.getName()))
{
cookie.setValue(null);
cookie.setPath("/");
cookie.setMaxAge(0);
res.addCookie(cookie);
break;
}
}
}
}catch(Exception ex)
{
ex.printStackTrace();
}
}
public static void addCookie(HttpServletResponse res,String cookieName,String cookieValue)
{
Cookie cookie = new Cookie(cookieName,cookieValue);
cookie.setPath("/");
//cookie.setMaxAge(3600*24*365);
//cookie.setSecure(true);//setSecure(true); 的情况下,只有https才传递到服务器端。http是不会传递的。
res.addCookie(cookie);
}
public static String getCookieByCookieName(HttpServletRequest req,String cookieName)
{
try
{
Cookie[] cookies = req.getCookies();
if(null != cookies)
{
for(Cookie cookie:cookies)
{
if(cookieName.equals(cookie.getName()))
{
return cookie.getValue();
}
}
}
}catch(Exception ex)
{
ex.printStackTrace();
}
return null;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy