`
清晨迎朝阳
  • 浏览: 64008 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
文章分类
社区版块
存档分类
最新评论

上下文(context)ActionContext介绍(在Struts2中)

 
阅读更多

      一种属性的有序序列,它们为驻留在环境内的对象定义环境。在对象的激活过程中创建上下文,对象被配置为要求某些自动服务,如同步、事务、实时激活、安全性等等。多个对象可以存留在一个上下文内。也有根据上下文理解意思的意思。

ActionContext介绍(在Struts2中)

 

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.

如果我要取得Servlet API中的一些对象,request,responsesession,应该怎么做?Strutx 2.0你可以有两种方式获得这些对象:IoC(控制反转Inversion of Control)方式和IoC方式.

A、非IoC方式

 要获得上述对象,关键Struts 2.0com.opensymphony.xwork2.ActionContext.我们可以通过它的静态方法getContext()获取当前 Action的上下文对象. 另外,org.apache.struts2.ServletActionContext作为辅助类(Helper Class),可以帮助您快捷地获得这几个对象.

HttpServletRequest request = ServletActionContext.getRequest();

HttpServletResponse response = ServletActionContext.getResponse();

HttpSession session = request.getSession();

 

如果你只是想访问session的属性(Attribute),你也可以通过ActionContext.getContext().getSession()获取或添加session范围(Scoped)的对象.

 

BIoC方式

要使用IoC方式,我们首先要告诉IoC容器(Container)想取得某个对象的意愿,通过实现相应的接口做到这点.具体实现,请参考例6 IocServlet.java.

6 classes/tutorial/NonIoCServlet.java

package tutorial;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

import com.opensymphony.xwork2.ActionSupport;

Public class NonIoCServlet extends ActionSupport {

private String message;

 

public String getMessage() {

return message;

}

HttpServletRequest request = ServletActionContext.getRequest();

HttpServletResponse response = ServletActionContext.getResponse();

HttpSession session = request.getSession();

 

@Override

public String execute() {

ActionContext.getContext().getSession().put("msg", "Hello World from Session!");[A2] 

 

StringBuffer sb =new StringBuffer("Message from request: ");

sb.append(request.getParameter("msg"));

 

sb.append("<br>Response Buffer Size: ");

sb.append(response.getBufferSize());

 

sb.append("<br>Session ID: ");

sb.append(session.getId());

 

message = sb.toString();  //转换为字符串。

return SUCCESS;

}

}   //LoginAction类似的方法。

 

6 classes/tutorial/IoCServlet.java

package tutorial;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;

import org.apache.struts2.interceptor.ServletResponseAware;

import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionContext;

import com.opensymphony.xwork2.ActionSupport;

publicclass IoCServlet extends ActionSupport implements SessionAware,   ServletRequestAware, ServletResponseAware {

private String message;

private Map att;

private HttpServletRequest request;

private HttpServletResponse response;

 

public String getMessage() {

return message;

}

public void setSession(Map att) {

this.att = att;

}

publicvoid setServletRequest(HttpServletRequest request) {

this.request = request;

}

publicvoid setServletResponse(HttpServletResponse response) {

this.response = response;

}

 

@Override

public String execute() {

att.put("msg", "Hello World from Session!");

 

HttpSession session = request.getSession();

 

StringBuffer sb =new StringBuffer("Message from request: ");

sb.append(request.getParameter("msg"));

sb.append("<br>Response Buffer Size: ");

sb.append(response.getBufferSize());

sb.append("<br>Session ID: ");

sb.append(session.getId());

 

message = sb.toString();

return SUCCESS;

}

}

6 Servlet.jsp

<%@ page contentType="text/html; charset=UTF-8" %>

<%@ taglib prefix="s" uri="/struts-tags"%>

<html>

<head>

<title>Hello World!</title>

</head>

<body>

<h2>

<s:property value="message" escape="false"/>

<br>Message from session: <s:property value="#session.msg"/>

</h2>

</body>

</html>

6 classes/struts.xmlNonIocServletIoCServlet Action的配置

<action name="NonIoCServlet" class="tutorial.NonIoCServlet">

<result>/Servlet.jsp</result>

</action>

<action name="IoCServlet" class="tutorial.IoCServlet">

<result>/Servlet.jsp</result>

</action>

 运行Tomcat,在浏览器地址栏中键入http://localhost:8080/Struts2_Action /NonIoCServlet.action?msg=Hello%20World! http://localhost:8080/Struts2_Action/IoCServlet.action?msg=Hello%20World!

 在Servlet.jsp,我用了两次property标志,第一次将escape设为false为了在JSP中输出<br>转行,第二次的value中的OGNL"#session.msg",它的作用与session.getAttribute("msg")等同.

 

 

附:ActionContext的常用方法(来自Struts2.0  API

(一)get

public Object get(Object key)

Returns a value that is stored in the current ActionContext by doing a lookup using the value's key.

Parameters:

key- the key used to find the value.

Returns:

the value that was found using the key or null if the key was not found.

 (二)put

public void put(Object key, Object value)

Stores a value in the current ActionContext. The value can be looked up using the key.

Parameters:

key- the key of the value.

value- the value to be stored.

 

(三)getContext

public static ActionContext getContext()

Returns the ActionContext specific to the current thread.

Returns:

the ActionContext for the current thread, is never null.

(四)getSession

public Map getSession()

Gets the Map of HttpSession values when in a servlet environment or a generic session map otherwise.

Returns:

the Map of HttpSession values when in a servlet environment or a generic session map otherwise.

 ()setSession

public void setSession(Map session)

Sets a map of action session values.

Parameters:

session- the session values.

 

 

Struts2action类继承

com.opensymphony.xwork2.ActionSupport类的常用方法

 

addFieldError  //该方法主要用于验证的方法之中

public void addFieldError(String fieldName,  String errorMessage)

Description copied from interface: ValidationAware

Add an error message for a given field.

Specified by:

addFieldErrorin interface ValidationAware

Parameters:

fieldName- name of field

errorMessage- the error message

validate

public void validate()

A default implementation that validates nothing. Subclasses should override this method to provide validations.

Specified by:

validatein interface Validateable

 

 


这一点比较的重要,例如:ActionContext.getContext().getSession().put("user", "value");

与右上角的是一个模式。

Java语法基础,使用stringBuffer

对属性(实例)设置setter方法。

方法的来源,见后面补充的常用方法:

public void setSession(Map session)

Sets a map of action session values. 设置session值,

Parameters:

session- the session values.

 

为当前的session,所以可以调用put方法。详细信息见补充的知识。

常用于校验登陆程序的账号和密码是否为空,可以加入addFieldError方法。例如public void validate() {

       if (null == login.getUserID() || "".equals(login.getUserID())) {          this.addFieldError("login.userID", "学号不能为空");       }

       if (null == login.getUserPassword()              || "".equals(login.getUserPassword())) {          this.addFieldError("login.userPassword", "密码不能为空");    }

    }

分享到:
评论
2 楼 jveqi 2014-02-20  
protected static void cleanUp(ServletRequest req) { 
 
  ... 
  ActionContext.setContext(null);//清除ActionContext实例 
  Dispatcher.setInstance(null);//清除Dispatcher实例(Dispatcher主要是完成将url解析成对应的Action) 
}


那岂不是  session 数据也清空了?
附:ActionContext ctx = ActionContext.getContext();

ctx.put("liuwei", "andy"); //request.setAttribute("liuwei", "andy");
Map session = ctx.getSession(); //session

HttpServletRequest request = ctx.get(org.apache.struts2.StrutsStatics.HTTP_REQUEST);
HttpServletResponse response = ctx.get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
1 楼 jveqi 2014-02-20  
有点迷惑。

是不是每个请求都需要经过 ActionContextCleanUp。。FilterDispatcher 然后处理action?

处理完action后,然后继续其他拦截器处理,然后ActionContextCleanUp拦截器处理,执行
 

相关推荐

    ActionContext介绍(在Struts2中)

    在Web应用程序开发中,除了将请求参数自动设置到Action的字段中,我们往往也需要在Action里直接获取请求(Request)或会话 (Session)的一些信息, 甚至需要直接对JavaServlet Http的请求(HttpServletRequest),响应...

    struts2中的ActionContext与ognl

    NULL 博文链接:https://lijiejava.iteye.com/blog/628636

    ActionContext在struts2.0中的详细应用

    ActionContext(com.opensymphony.xwork.ActionContext)是Action执行时的上下文,上下文可以看作是一个容器(其实我们这里的容器就是一个Map而已),它存放放的是Action在执行时需要用到的对象

    Struts2中Servlet的配置

    1、在struts2的action中可以通过实现ServletResponseAware/ServletResquestAware接口 (org.apache.struts2.inteceptor.ServletResponseAware/ServletResquestAware)直接访问 HttpServletResponse/HttpServletRequest...

    基于struts2注册登录ActionContext.zip

    struts2大量使用拦截器来处理请求,从而允许与业务逻辑控制器 与 servlet-api分离,避免了侵入性(所谓侵入性就是指的这个架构设计出来的部件对系统的影响范围,标签库几乎可以完全替代JSTL的标签库,并且 struts2.x...

    struts2_OGNL表达式ActionContext及valuesStack

    struts2 OGNL,struts2 表达式语言,Struts2 中OGNL表达式的用法,Struts2 #,表达式语言的好处,Struts2 $,struts2 井号,星号,百分号

    struts2OGNL表达式ActionContext及valuesStack.pdf

    struts2OGNL表达式ActionContext及valuesStack.pdf

    Struts2 in action中文版

    9.1 为什么在Struts 2中使用Spring 196 9.1.1 依赖注入能做些什么 197 9.1.2 Spring如何管理对象和注入依赖 199 9.1.3 使用接口隐藏实现 200 9.2 将Spring添加到Struts 2 202 9.2.1 让Spring管理动作、拦截器和结果...

    struts2流程与流程图

    一个请求在Struts 2框架中的处理大概分为以下几个步骤。  客户端提交一个(HttpServletRequest)请求,如上文在浏览器中输入 http://localhost: 8080/bookcode/ch2/Reg.action就是提交一个(HttpServletRequest)...

    Struts2整合SiteMesh技巧

    概述 Struts 2.0提供一个Sitemesh插件... 缺省情况下,sitemesh假定装饰器文件保存在应用上下文根路径下的decorators目录下,如果采用如上配置,装饰器文件应该是ftl格式,如果需要使用其他格式,需要更改过滤器配置。

    Struts2通过使用ActionContext类获取request和response对象

    NULL 博文链接:https://zhouhaitao.iteye.com/blog/1126042

    Struts2 ActionContext 中的数据详解

    主要介绍了Struts2 ActionContext 中的数据详解,需要的朋友可以参考下

    Struts2_TypeConvertion

    在Struts2中底层的session都被封装成了Map类型,我们称之为SessionMap,而平常我们所说的session则是指HttpSession对象,具体的获得方法如下所示。 A.Map session=ActionContext.getSession(); B.Map session=(Map...

    struts2验证码完整实例

    1、页面加载后,想后台发出生产验证码图片的请求,并在前台显示验证码图片,同时将验证码上的数字 通过ActionContext.getContext().getSession().put("random", randomNum.getRandomCode())将数字存放到session当中 2...

    西安领航核心项目Struts2重点、难点总结

    对Struts2框架中的相关知识还有困惑的同学有福了,此次上传的是西安领航何足道老师的核心项目Struts2部分的重点难点的归纳总结,他对Struts2理解非常深刻,讲的非常的详细易懂,堪称经典。主要包括的知识有Action的...

    Struts2 学习笔记

    01 Struts2-Action 5 一、 Struts作用: 5 二、 搭建Struts2的运行环境: 5 三、 Namespace 6 四、 标签 6 五、 Action 6 六、 路径问题的说明 8 七、 Action的动态调用方法 8 八、 Action通配符(wildcard)的配置 9 ...

    OGNL表达式语言.txt

    访问上下文中的对象需要使用#符号标注命名空间,如#application、#session 另外OGNL会设定一个根对象(root对象),在Struts2中根对象是ValueStack。 如果访问根对象中的对象的属性,则可以省略#命名空间。

    struts2-junit-plugin-2.1.8.jar

    可解决java.lang.NoSuchMethodError: com.opensymphony.xwork2.ActionContext.get(Ljava/lang/Object;)Ljava/lang/Object; java.lang.ClassNotFoundException: com.opensymphony.xwork2.util.TextUtils struts2.1.8...

    Struts2帮助```````

    01 Struts2-Action 5 一、 Struts作用: 5 二、 搭建Struts2的运行环境: 5 三、 Namespace 6 四、 标签 6 五、 Action 6 六、 路径问题的说明 8 七、 Action的动态调用方法 8 八、 Action通配符(wildcard)的配置 9 ...

    OGNL表达式struts2标签

    OGNL(Object-Graph Navigation Language),大概可以理解为:对象图形化导航语言。是一种可以方便地操作对象属性的开源表达式语言。... 4、访问OGNL上下文(OGNL context)和ActionContext; 5、操作集合对象。

Global site tag (gtag.js) - Google Analytics