package shop.alien.util.common;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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

/**
 * Web工具类
 * 用于在非Controller层获取HttpServletRequest和HttpServletResponse
 *
 * @author system
 */
public class WebTool {

    /**
     * 获取当前请求的HttpServletRequest
     *
     * @return HttpServletRequest
     * @throws IllegalStateException 如果当前不在Web请求上下文中
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new IllegalStateException("当前不在Web请求上下文中，无法获取HttpServletRequest");
        }
        return attributes.getRequest();
    }

    /**
     * 获取当前请求的HttpServletResponse
     *
     * @return HttpServletResponse
     * @throws IllegalStateException 如果当前不在Web请求上下文中
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new IllegalStateException("当前不在Web请求上下文中，无法获取HttpServletResponse");
        }
        return attributes.getResponse();
    }
}

