OGNL表达式语言(#号的用法)
用法1:访问OGNL上下文和Action上下文,#相当ActionContext.getContext()
1、 如果访问其他Context中的对象,由于他们不是根对象,所以在访问时,
需要添加#前缀。
也可写为#request[‘userName’]或#session[‘userName’]或#appliction[‘userName’]
用法1:访问OGNL上下文和Action上下文,#相当ActionContext.getContext()
2 、OGNL会设定一个根对象(root对象),在Struts2中根对象就是ValueStack
(值栈)。如果要访问根对象(即ValueStack)中对象的属性,则可以省略
#命名对象,直接访问该对象的属性即可。
Action中代码:
ValueStackvalueStack=ServletActionContext.getContext().getValueStack();
valueStack.set("msg","msg_xxx");
Jsp页面:
valueStack:<s:property value="msg"/><br>
OGNL表达式语言(%用法)
“%”符号的用途是在标签的属性值被理解为字符串类型时,告诉执行环境%{}里的是OGNL表达式。
形式一: { }中ognl表达式
Action中的代码:
ServletActionContext.getRequest().setAttribute("username","username_request");
jsp页面:
<s:textfieldname="name" label="%{#request.username}"/>
运行结果是
username_request:<inputtype="text" name="name" value=""id="name"/>
形式二:{ }中值用 ’ ’引起来,这是不再是ogle表达式,而是普通的字符串
jsp页面:
<s:textfieldname="name" label="%{'foo'}"/>
运行结果是
foo :<input type="text"name="name" value="" id="name"/>
OGNL表达式语言($用法)
“$”有两个主要的用途
* 用于在国际化资源文件中,引用OGNL表达式
* 在Struts 2配置文件中,引用OGNL表达式
在struts2配置文件中引用ognl表达式 ,引用request等作用域中的值
Action中的代码:
ServletActionContext.getRequest().setAttribute("msgxx","msg_request");
struts.xml文件中
<package name="ognl" namespace="/ognl"extends="struts-default" >
<actionname="ognlAction_*"class="cn.itcast.ognl.OgnlAction"method="{1}">
<result name="ognl">/ognl/ongl.jsp?msg=${#request.msgxx}</result>
</action>
</package>
jsp页面:
parametersMsg:<s:propertyvalue="#parameters.msg[0]"/>
运行结果是
msg_request
在struts2配置文件中引用ognl表达式 ,引用值栈的值
Action中的代码:
valueStack.set("msgxx","msg_valueStack");
struts.xml文件中
<package name="ognl" namespace="/ognl"extends="struts-default" >
<actionname="ognlAction_*"class="cn.itcast.ognl.OgnlAction"method="{1}">
<result name="ognl">/ognl/ongl.jsp?msg=${msgxx}</result>
</action>
</package>
jsp页面:
parametersMsg:<s:propertyvalue="#parameters.msg[0]"/>
运行结果是
msg_valueStack