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

org.hepeng.commons.web.util.RequestTokenUtils Maven / Gradle / Ivy

The newest version!
package org.hepeng.commons.web.util;

import org.hepeng.commons.util.UUIDUtils;
import org.springframework.util.Assert;

import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * @author he peng
 */
public class RequestTokenUtils {

    private static final String HTTP_REQUEST_TOKEN_KEY = System.getProperty("http.request.token");

    private RequestTokenUtils() {}

    /**
     * 设置服务端 http request token 的值
     * @param session {@link HttpSession} 实例对象
     * @return 返回 token 的值
     */
    public static String setRequestToken(HttpSession session) {
        Assert.notNull(session , "session == null");
        String token = genToken();
        session.setAttribute(HTTP_REQUEST_TOKEN_KEY, token);
        return token;
    }

    /**
     * 从 {@link HttpSession} 中获取服务端存储的 http request token
     * @param session   {@link HttpSession} 实例对象
     * @return 返回 token 的值
     */
    public static String getRequestToken(HttpSession session) {
        Assert.notNull(session , "session == null");
        Object token = session.getAttribute(HTTP_REQUEST_TOKEN_KEY);
        return Objects.nonNull(token) ? token.toString() : "";
    }

    /**
     * 从 {@link HttpSession} 中移除 http request token
     * @param session   {@link HttpSession} 实例对象
     */
    public static void removeRequestToken(HttpSession session) {
        Assert.notNull(session , "session == null");
        session.removeAttribute(HTTP_REQUEST_TOKEN_KEY);
    }

    /**
     * 生成一个 http request token 值
     * @return  返回一个 32 位的 uuid 字符串
     */
    private static String genToken() {
        return UUIDUtils.uuid32();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy