java里面有关Session和cookie的一些操作方法

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;


    protected HttpServletRequest getRequest() {

        return ServletActionContext.getRequest();
    }

    protected HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }

    protected HttpServletResponse getResponse() {
        return ServletActionContext.getResponse();
    }

    /**
     * 放一个对象到session里
     *
     * @param sessionKey
     * @param obj
     */
    public void setObjToSession(String sessionKey, Object obj) {
        ActionContext context = ActionContext.getContext();
        Map<String, Object> sessionMap = context.getSession();
        sessionMap.put(sessionKey, obj);
    }

    public Object getObjFromSession(String sessionKey) {
        ActionContext context = ActionContext.getContext();
        Map<String, Object> sessionMap = context.getSession();
        Object obj = sessionMap.get(sessionKey);
        return obj;
    }

    public void removeFromSession(String key) {
        ActionContext context = ActionContext.getContext();
        Map<String, Object> sessionMap = context.getSession();
        sessionMap.remove(key);
        
    }

    /**
     * 往cookie里塞值
     *
     * @param key
     * @param value
     * @param time
     */
    public void addCookie(String key, String value, int time) {
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(time);
        cookie.setPath("/");
        ServletActionContext.getResponse().addCookie(cookie);
    }

    /**
     * 根据key 删除cookie
     *
     * @param key
     */
    public void removeCookie(String key) {
        Cookie cookie = new Cookie(key, null);
        cookie.setMaxAge(0);
        cookie.setPath("/"); // 项目所有目录均有效,这句很关键,否则不敢保证删除
        ServletActionContext.getResponse().addCookie(cookie);
    }

    /**
     * 根据key 从cookie中获取值
     *
     * @param key
     * @return
     */
    public String getValueFromCookie(String key) {
        Cookie cookies[] = ServletActionContext.getRequest().getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie != null && StringUtils.equals(key, cookie.getName()))
                    return cookie.getValue();
            }
        }
        return null;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值