All Downloads are FREE. Search and download functionalities are using the official Maven repository.

shz.spring.session.SessionHolder Maven / Gradle / Ivy

There is a newer version: 2023.2.5
Show newest version
package shz.spring.session;

import shz.core.msg.ClientFailure;
import shz.spring.ServletHelp;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.function.Consumer;

public final class SessionHolder {
    private SessionHolder() {
    }

    public static final String SESSION = "SESSION_ATTRIBUTE_NAME_SESSION";
    public static final String SESSION_TRACE_NO = "SESSION_HEADER_TRACE_NO";

    public static Session get(ServletRequest request) {
        return request == null ? null : (Session) request.getAttribute(SESSION);
    }

    public static Session get() {
        HttpServletRequest request = ServletHelp.getRequest();
        return request == null ? null : get(request);
    }

    public static Session getNonNull(ServletRequest request) {
        return ClientFailure.FORBIDDEN.requireNonNull(get(request));
    }

    public static Session getNonNull() {
        return getNonNull(ServletHelp.getRequest());
    }

    public static void set(ServletRequest request, Consumer setter) {
        if (setter != null) {
            Session session = get(request);
            if (session != null) setter.accept(session);
        }
    }

    public static void set(Consumer setter) {
        set(ServletHelp.getRequest(), setter);
    }

    public static void setException(ServletRequest request, int code, String msg) {
        set(request, session -> {
            if (session.getException() == Boolean.FALSE) {
                session.setException(Boolean.TRUE);
                session.setExceptionCode(code);
                session.setExceptionMsg(msg);
            }
        });
    }

    public static void setException(int code, String msg) {
        setException(ServletHelp.getRequest(), code, msg);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy