关于Java Spring MVC中快速获取HttpServletRequest和HttpServletResponse的说明

在Spring MVC中,为了能够随时取到当前请求的对象数据,可以通过@Autowired注解法获取,或者通过RequestContextHolder的静态方法getRequestAttributes获取相关变量,从而获取HttpServletRequest和HttpServletResponse对象。

一、获取HttpServletRequest:

// 注解法
@Autowired
protected HttpServletRequest request;

// RequestContextHolder法
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getResponse();

二、获取HttpServletResponse:

// 注解法
@Autowired
protected HttpServletResponse response;

// RequestContextHolder法
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletResponse response = attributes.getResponse();

发表评论