springmvc-响应
如何从bean访问响应对象?要获取请求对象,我使用以下命令springmvc-响应,spring,spring-mvc,Spring,Spring Mvc,如何从bean访问响应对象?要获取请求对象,我使用以下命令 ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); 响应对象是否有与上述类似的功能?如果您处于web应用程序上下文中(看起来是这样),则可以自动连接HttpServletRequest或HttpServletResponse 将注入来自当前请求范围
ServletRequestAttributes attr = (ServletRequestAttributes)
RequestContextHolder.currentRequestAttributes();
响应对象是否有与上述类似的功能?如果您处于web应用程序上下文中(看起来是这样),则可以自动连接HttpServletRequest或HttpServletResponse 将注入来自当前请求范围的请求/响应
@Component
public class SomeComponentInAWebApplicationContext {
@Autowired
private HttpServletRequest request;
@Autowired
private HttpServletResponse response;
...
}
我看到答案已被接受,但我不清楚这是否可行——这些依赖项在春季从何而来?尝试时,它按预期失败:原因是:org.springframework.beans.factory.NoSuchBeanDefinitionException:找不到依赖项类型为[javax.servlet.http.HttpServletResponse]的匹配bean。我遗漏了什么吗?该组件必须是WebApplicationContext的一部分,即从-servlet.xml上下文启动的组件。请求和响应只连接一次。请在此处查看Bozho的答案: