首页>代码>Springboot开发的精简博客系统 >/noteblogv4-master/src/main/java/me/wuwenbin/noteblogv4/config/application/NBContext.java
package me.wuwenbin.noteblogv4.config.application;

import me.wuwenbin.noteblogv4.model.constant.NoteBlogV4;
import me.wuwenbin.noteblogv4.model.entity.permission.NBSysUser;
import me.wuwenbin.noteblogv4.util.CookieUtils;
import me.wuwenbin.noteblogv4.util.NBUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 全局的上下文对象
 * 用于操作session和cookie
 * created by Wuwenbin on 2018/7/16 at 12:25
 *
 * @author wuwenbin
 */
@Component
public class NBContext extends ConcurrentHashMap<String, NBSession> {

    private static ConcurrentHashMap<String, Object> applicationContext = new ConcurrentHashMap<>(100);

    public void setSessionUser(HttpServletRequest request, HttpServletResponse response, NBSysUser sessionUser) {
        NBSession session = NBSession.builder()
                .sessionUser(sessionUser)
                .expired(false)
                .host(NBUtils.getRemoteAddress(request))
                .build();
        Cookie cookie = CookieUtils.getCookie(request, NoteBlogV4.Session.SESSION_ID_COOKIE);
        if (cookie != null) {
            session.setId(cookie.getValue());
        }
        CookieUtils.setCookie(response, NoteBlogV4.Session.SESSION_ID_COOKIE, session.getId(), -1);
        put(session.getId(), session);
    }

    public NBSysUser getSessionUser(String uuid) {
        Optional<NBSession> user = Optional.ofNullable(get(uuid));
        return user.map(NBSession::getSessionUser).orElse(null);
    }

    public void removeSessionUser(String uuid) {
        super.remove(uuid);
    }

    public void clearAll() {
        super.clear();
    }

    public void setApplicationObj(String key, Object value) {
        applicationContext.put(key, value);
    }

    public <T> T getApplicationObj(String key) {
        //noinspection unchecked
        return (T) applicationContext.get(key);
    }

    public void removeApplicationObj(String key) {
        applicationContext.remove(key);
    }

}
最近下载更多
zolscy  LV24 2024年12月9日
yayacui  LV2 2024年10月28日
angaochong  LV5 2024年10月23日
y1214435276  LV9 2024年9月26日
Peny_ZH  LV5 2024年9月22日
murphy  LV7 2024年7月3日
xunxia  LV7 2024年6月29日
来一杯西瓜冰咩  LV6 2024年5月13日
qiangmin1223  LV12 2024年4月24日
xiaokang1  LV10 2024年4月23日
最近浏览更多
orang801  LV2 3月4日
f22m1a2b2  LV17 2月5日
nightstarshii 1月26日
暂无贡献等级
Long1022gnoL 1月17日
暂无贡献等级
莓冰淇淋 2024年12月26日
暂无贡献等级
dengge123  LV14 2024年12月13日
haomc052829  LV4 2024年12月3日
cpk159  LV8 2024年11月28日
krispeng  LV14 2024年11月20日
xianyu091012  LV5 2024年11月18日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友