ActionContext(Action上下文)

Web 应用程序开发中,除了将请求参数自动设置到 Action 的字段中,我们往往也需要在 Action 里直接获取请求 (Request) 或会话( Session )的一些信息 甚至需要直接对 JavaServlet Http 的请求( HttpServletRequest )、响应 (HttpServletResponse) 操作。
我们需要在 Action 中取得 request 请求参数“ username ”的值:
ActionContext context = ActionContext.getContext();
Map params = context.getParameters();
String username = (String) params.get(“username”);
ActionContext com.opensymphony.xwork.ActionContext )是 Action 执行时的上下文,上下文可以看作是一个容器(其实我们这里的容器就是一个 Map 而已),它存放放的是 Action 在执行时需要用到的对象
 
一般情况,我们的 ActionContext 都是通过: ActionContext context = (ActionContext) actionContext.get(); 来获取的。我们再来看看这里的 actionContext 对象的创建: static ThreadLocal actionContext = new ActionContextThreadLocal(); ActionContextThreadLocal 是实现 ThreadLocal 的一个内部类。 ThreadLocal 可以命名为“线程局部变量”,它为每一个使用该变量的线程都提供一个变量值的副本,使每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突。这样,我们 ActionContext 里的属性只会在对应的当前请求线程中可见,从而保证它是线程安全的。
 
 
下面我们看看怎么通过 ActionContext 取得我们的 HttpSession
Map session = ActionContext.getContext().getSession()
 
ServletActionContext com.opensymphony.webwork. ServletActionContext ),这个类直接继承了我们上面介绍的 ActionContext ,它提供了直接与 JavaServlet 相关对象访问的功能,它可以取得的对象有:
1、    javax.servlet.http.HttpServletRequest HTTPservlet 请求对象
2、    javax.servlet.http.HttpServletResponse; HTTPservlet 相应对象
3、    javax.servlet.ServletContext Servlet  上下文信息
4、    javax.servlet.ServletConfig Servlet 配置对象
5、    javax.servlet.jsp.PageContext Http 页面上下文
 
 
下面我们看看几个简单的例子,让我们了解如何从 ServletActionContext 里取得 JavaServlet 的相关对象:
1、    取得 HttpServletRequest 对象:
HttpServletRequest request = ServletActionContext. getRequest();
2、    取得 HttpSession 对象:
HttpSession session = ServletActionContext. getRequest().getSession();
 
ServletActionContext ActionContext 有着一些重复的功能,在我们的 Action 中,该如何去抉择呢?我们遵循的原则是:如果 ActionContext 能够实现我们的功能,那最好就不要使用 ServletActionContext ,让我们的 Action 尽量不要直接去访问 JavaServlet 的相关对象。在使用 ActionContext 时有一点要注意:不要在 Action 的构造函数里使用 ActionContext.getContext() ,因为这个时候 ActionContext 里的一些值也许没有设置,这时通过 ActionContext 取得的值也许是 null

猜你喜欢

转载自blog.csdn.net/u013057786/article/details/22676909