Struts2 “.”和“[]”操作符:获取ActionContext中的所有内容

  • 内容
  • 评论
  • 相关

Struts2 框架在 OGNL 的基础上得到了增强,提高了 Struts2 对数据的访问能力。在 Struts2 框架中,OGNL 上下文作用于 Struts2 中的 ActionContext 对象,ActionContext 对象是 Struts2 框架中的一个核心对象。

在 Struts2 框架中,当接收到一个 Action 请求时,Struts2 框架会创建 ActionContext 对象并示例化值栈等对象,由于 OGNL 上下文作用于 ActionContext 对象,因此通过 OGNL 表达式可以获取 ActionContext 中的所有内容,而获取这些内容时使用的是“.”和“[]”操作符。

语法:

#application|request|session|attr|parameters.name

#application|request|session|attr|parameters.['name']

这两个操作符用于获取 ActionContext中 的所有内容,即获取 application、request、session、attr 和 parameters。

上述代码分别相当于调用了 application.getAttribute("name")、request.getAttribute("name")、session.getAttribute("name")、request.getParameter("name")方法。

示例

本示例使用“#”来读取 ActionContext 对象中的一些数值,然后将获取的数据输出到页面中。

创建 OgnlAction.action 文件,在其中定义变量和编写 get 方法和 set 方法。

创建 index.jsp 文件,应用“#”获取相应资源的属性,关键代码如下:

<body>//使用“#”获取属性
  <p>request.userName:<s:property value="#request.userName"/></p>
  <p>session.userName:<s:property value="#session.userName"/></p>
  <p>application.userName:<s:property value="#application.userName"/></p>
  <p>attr.userName:<s:property value="#attr.userName"/></p>
</body>}

运行结果如下:
request.userName:这个属性来自request
session.userName:这个属性来自session
application.userName:这个属性来自application

本文标题:Struts2 “.”和“[]”操作符:获取ActionContext中的所有内容

本文地址:https://www.hosteonscn.com/6401.html

评论

0条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注