ContextMap、ActionContext以及ServletActionContext

ContextMap:它存了一次请求所需的所有数据,包括但不限于:

request--是一个map类型

session--一个map类型

application--一个map类型

valuestack(值栈)

action--表示当前执行的动作类实例,不用关心,因为在valuestack中有这个对象

parameters--包含了参数,但struts2中都是框架帮我们封装参数了,有modeldriven了,所以也不管

attr(page    request    session    application)--也不管


ActionContext:ContextMap是Map<String,Object>类型,所以从它里面获取的request,session,application都是Object类型。可是它们实际上都是Map类型,所以这时候一个工具类出现了--ActionContext,它帮我们封装好了方法,我们用它获取的request等就是Map<String,Object>类型,不需要我们再强转了。看它的源码可以知道,在它的构造方法中就将contextMap对象传进来了,然后再通过contextMap来获取对应对象。ActionContext对象在请求经过过滤器的时候创建,但是注意,只有那种action请求才会创建,普通的访问jsp\html这种请求过滤器直接放行了,是不会有actionContext对象创建的,actionContext对象创建以后会绑定到当前线程中,所以我们在后面的action类中直接通过ActionContext.getContext()就可以获取到当前线程的actionContext对象了。

ActionContext context = ActionContext.getContext();
Map<String,Object> app_map = context.getApplication();
		app_map.put("xixi", "xixixixixixixixxi");


ServletActionContext:专门拿servletAPI的一个工具类,继承了ActionContext.

	request = ServletActionContext.getRequest();
	response = ServletActionContext.getResponse();
	HttpSession session = request.getSession();
	application = ServletActionContext.getServletContext();

注:ActionContext和ServletActionContext都可以拿到servlet中对应的对象,但是ActionContext中有session而没有response,ServletActionContext有response没有session,需要拿session需要通过request.getSession()获取。

另外两种类获取到相应的对象类型不一样,ActionContext获取到的request,session,application都是Map<String,Object>类型,存数据都是用request.set("","")的形式,而ServletActionContext获取到的对象则是servlet中原生的域对象,存数据时用的  request.setAttribute("",""),其实可以把ActionContext方式获得的域对象看作是把原生的稍微封装了一下,来个栗子:

public class Dodebug extends ActionSupport {
	public String doDebug() {
		ActionContext context = ActionContext.getContext();
		
		ServletContext app_servlet = ServletActionContext.getServletContext();
		app_servlet.setAttribute("hehe","hehehehehehehehehehe");
		
		Map<String,Object> app_map = context.getApplication();
		app_map.put("xixi", "xixixixixixixixxi");
		
		System.out.println(app_servlet == app_map);
		return SUCCESS;
	}
}

猜你喜欢

转载自blog.csdn.net/dimples_qian/article/details/81020453