通过spring,在项目的任意位置获取当前Request


需要引入:

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();
    }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM