package com.app.framework.core.utils.request;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Session工具类
 */
public class SessionUtil {

    /**
     * 登录会话名称
     */
    public static final String OPERATOR_CONTEXT = "operator_context";


    /**
     * 将数据存放到session中
     *
     * @param request
     * @param name    名称
     * @param o       数据
     */
    public static void set(HttpServletRequest request, String name, Object o) {
        if (request != null && name != null && o != null) {
            request.getSession().setAttribute(name, o);
        }
    }

    /**
     * 获取session中的数据
     *
     * @param request
     */
    public static <T> T get(HttpServletRequest request, String name) {
        if (request == null || name == null) return null;
        try {
            HttpSession session = request.getSession();
            if (session == null) return null;
            Object o = session.getAttribute(name);
            if (o == null) return null;
            return (T) o;
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * 从session中移除数据
     */
    public static void remove(HttpServletRequest request, String name) {
        HttpSession session = request.getSession();
        if (session != null && name != null) {
            session.removeAttribute(name);
        }
    }


    /**
     * 将当前用户存放到session中
     *
     * @param request
     * @param loginUser
     */
    public static <T> void setCurrentUser(HttpServletRequest request, T loginUser) {
        set(request, OPERATOR_CONTEXT, loginUser);
    }

    /**
     * 获取当前登录的用户
     *
     * @param request
     */
    public static <T> T getCurrentUser(HttpServletRequest request) {
        return get(request, OPERATOR_CONTEXT);
    }

    /**
     * 从session中移除当前用户
     */
    public static void removeCurrentUser(HttpServletRequest request) {
        remove(request, OPERATOR_CONTEXT);
    }
}
