Java-Spring-获取Request,Response对象

时间:2024-03-29 17:06:02

转载自:https://www.cnblogs.com/bjlhx/p/6639542.html

第一种、参数

@RequestMapping("/test")
@ResponseBody
public void saveTest(HttpServletRequest req, HttpServletResponse resp){  
}

第二种、注解

@Autowired
private HttpServletRequest request;

第三种、上下文获取

1、在web.xml配置监听器

<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

2、程序使用

HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
HttpServletResponse resp = ((ServletWebRequest)RequestContextHolder.getRequestAttributes()).getResponse();