需要引入:
import javax.servlet.http.HttpServletRequest; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes;
使用方法:
1 public static HttpServletRequest getRequest(){ 2 ServletRequestAttributes ra= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 3 HttpServletRequest request = ra.getRequest(); 4 return request; 5 }
如果对安全有特别要求,做如下改进:
/** * * @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(); }
原文:http://www.cnblogs.com/flying607/p/5128088.html