需要引入:
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();
}