通過spring,在專案的任意位置獲取當前Request

劍握在手發表於2016-01-13

需要引入:

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

使用方法:

public static HttpServletRequest getRequest(){
    ServletRequestAttributes ra= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request =  ra.getRequest();
    return request;
}

如果對安全有特別要求,做如下改進:

/**
     * 
     * @Title: getCurrentRequest
     * @author:liuyx 
     * @date:2016年1月13日下午6:14:43
     * @Description: 獲取當前request
     * @return
     * @throws IllegalStateException 當前執行緒不是web請求丟擲此異常.
     */
    public static HttpServletRequest getCurrentRequest() throws IllegalStateException {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attrs == null) {
            throw new IllegalStateException("當前執行緒中不存在 Request 上下文");
        }
        return attrs.getRequest();
    }

 

相關文章