RequestUtils.java 2.03 KB
package org.nafmii.utils;

import org.nafmii.constant.HttpClientHeaderEnum;
import org.nafmii.constant.MessageEnum;
import org.nafmii.exception.BusinessException;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequestUtils {

    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
    }

    public static HttpServletResponse getResponse() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        return response;
    }

    public static Long getUserId(){
        String userId = getRequest().getHeader(HttpClientHeaderEnum.USER_HEADER_USER_ID.getCode());
        if (!StringUtils.isEmpty(userId)){
            try {
                return Long.valueOf(userId);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }

    public static String getToken(){
        String token = getRequest().getHeader(HttpClientHeaderEnum.USER_HEADER_USER_TOKEN.getCode());
        return StringUtils.isEmpty(token) ? null : token;
    }

    /**
     * 校验是否登录,登录返回用户ID
     * @return Long
     */
    public static Long checkLoginStatus(){
        Long userId = getUserId();
        String token = getToken();
        if (userId == null || StringUtils.isEmpty(token)){
            throw new BusinessException(MessageEnum.NO_LOGIN.getCode(), MessageEnum.NO_LOGIN.getRemarks());
        }
        return userId;
    }
}