1.通过注解获取(很简单,推荐)
public class HelloController {
@Autowired
protected HttpServletRequest request; //这里可以获取到request
}
2.在web.xml中配置一个监听
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
Java代码
HttpServletRequest request =
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
3.直接在参数中传递(此方法不好用,不建议使用):
public String helloController(HttpServletRequest request)
4.我曾经使用的方式@ModelAttribute方式
public abstract class BaseController {
protected HttpServletRequest request;
protected HttpServletResponse response;
protected HttpSession session;
protected ServletContext application;
@ModelAttribute
public void initServletApi(HttpServletRequest request,HttpServletResponse response){
this.request = request;
this.response = response;
this.session = request.getSession();
this.application = this.session.getServletContext();
}
}