整个应用中只有一个ServletContext对象,其实可以说代表的是web.xml。
1.多个servlet中间可以使用它来传递数据:
2.获取web.xml中的配置信息:
param>
<param-name>encodingparam-name>
<param-value>GBKparam-value>
param>
String initParameter = this.getServletContext().getInitParameter("encoding");
3.获取资源路径
getRealPath() 方法可以定位到web程序根路径
4.请求转发
ServletContext application = this.getServletContext();
RequestDispatcher requestDispatcher = application.getRequestDispatcher("/servletDemo2");
requestDispatcher.forward(request, response);
下面的A、B、C是代表客户端的cookie,服务器端的A、B、C代表session,D代表servletContext。
cookie是客户端技术,程序把每个用户的数据以cookie的形式写给用户各自的浏览器。当用户使用浏览器再去访问服务器中的web资源时,就会带着各自的数据去。这样,web资源处理的就是各自用户的数据了。
session是服务端技术,利用这个技术,服务器在运行时可以为每一个用户的浏览器创建一个其独享的httpSession对象,由于session为用户浏览器独享,所以用户在访问服务器的web资源时,可以把各自的数据放在各自的session中,当用户再去访问服务器中其他web资源时,其他web资源再从用户各自的session中取出数据为用户服务。
可以在request中获取所有cookie,并通过getName方法判别,可以调用response的addCookie给浏览器添加cookie。
可以在request对象中获取Session对象,并使用此对象做一系列操作。
提供了对JSP页面所有对象及命名空间的访问,也就是说用它可以访问到本页面所有的其他对象,例如request,response,session,application对象等;
${pageContext.request.contextPath}
两个对象都是struts2提供的用于操作web的对象。
ActionContext是Action执行时的上下文,里面存放着Action在执行时需要用到的对象,他将许多web常用对象封装成的Map,如ServletContext,Session,Request.
比如将HttpSession对象重新包装成了一个Map对象,里面存放着Session中的数据,提供这个Map给Action使用,而不用Action直接和底层的HttpSession打交道。也正是因为框架的包装,让Action可以完全的和Web层解耦。
//获得request
Map<String,Object> requestScope = (Map<String,Object>)ActionContext.getContext().get("request");
//获得session
Map<String, Object> sessionScope = ActionContext.getContext().getSession();
//获取application
Map<String, Object> application = ActionContext.getContext().getApplication();
//获得参数
Map<String, Object> params = ActionContext.getContext().getParameters();
ServletActionContext这个类直接继承了ActionContext,当然也继承了它父类的很多功能,比如:对OgnlValueStack、Action名字等的访问。更重要的是,它还提供了直接访问Servlet的相关对象的功能,它可以取得的对象有:
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
ServletContext servletContext = ServletActionContext.getServletContext();
PageContext pageContext = ServletActionContext.getPageContext();
HttpSession session = ServletActionContext.getRequest().getSession();
ActionContext和ServletActionContext有着一些重复的功能,都能够获取到Web对象的数据,但是又有些不同。
通常情况下,可以这么认为:ActionContext主要负责值的操作;ServletActionContext主要负责获取Servlet对象。
那么在Action中,该如何去抉择呢?建议的原则是:
优先使用ActionContext 只有ActionContext不能满足功能要求的时候,才使用ServletActionContext 总之,要尽量让Action与Web无关,这对于Action的测试和复用都是极其有好处的。
是spring的核心对象,BeanFactory的子接口,实际上跟web没关系,用于获取spring容器的元素和配置。
ClassPathXmlApplicationContext 用具加载classpath(类路径,src)下指定xml
FileSystemXmlApplicationContext 用具加载指定盘浮下xml
在springMvc中可以直接将request和response作为参数传入Controller的action中,从而进行相关web操作。
public String hello(HttpServletRequest request,HttpServletResponse response)
springMvc中获取ServletContex对象可以使用如下方式:
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
ServletContext servletContext = webApplicationContext.getServletContext();