Java中获取request对象的几种方法
1.通过注解获取(很简单,推荐):
public class Hello {
@Autowired
HttpServletRequest request; //这里可以获取到request
}
2.在web.xml中配置一个监听:
spring boot中不需要配置监听,直接使用第二步获得获取即可,还可以获取response
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
java代码:(spring自带的,在实际中用到过这个,推荐使用)
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
3.直接在参数中传递(此方法不好用,不建议使用):
public String hello(HttpServletRequest request)
4.如果有Struts:
HttpServletRequest request = ServletActionContext.getRequest();