struts2中的action访问web对象

来源:互联网 发布:户外轨迹软件 编辑:程序博客网 时间:2024/04/25 14:36

Struts2Action就是一个普通的POJO对象,它和Web对象requestresponsesessionapplication没有耦合在一起,这样便于单独测试Action,那么我们在Action中如何访问

这些web对象呢?

访问这些web内部对象有2种方式

1、直接访问Web对象

 

Struts2框架提供org.apache.struts2.ServletActionContext辅助类来获得web对象。HttpServletRequest request = ServletActionContext.getRequest();

 

HttpServletResponse response = ServletActionContext.getResponse();

 

HttpSession session = request.getSession();

 

ServletContext application = ServletActionContext.getServletContext();

       2Action访问ActionContext

 

com.opensymphony.xwork2.ActionContext是一个Action执行的上下文,Action执行期间所用到的对象都保存在ActionContext中,例如session、参数等,并且ActionContext是一个局部线程变量,不用担心Action的线程安全。

ActionContext context = ActionContext.getContext();

 该类的常用方法见表1-3所示:

 

1-3 ActionContext中的常用方法
struts2中的action访问web对象


这种方法使用的所有对象和Web对象没有直接联系,所以在测试的时候也

是很方便的,我们推荐在程序中使用此方法来访问web对象。