In this tutorial you will learn about the Struts 2 OGNL and its application with practical example.
Struts 2 OGNL
OGNL is the Object Graph Navigation Langauge.It is an expression language for getting and setting properties of Java Objects, plus other extras like list project and selection and lambda expressions. For getting and setting properties you can use same expression.
The Struts2 framework sets the OGNL context to be our ActionContext, and the value stack to be the OGNL root object.
Accessing the Action Property: We can directly access the action property like below code.
1 |
<s:property value="postalcode "/> |
Where postalcode is the property key
Accessing Non ActionContext Object : Other (non-root) objects in the ActionContext can be rendered use the # notation. Like below code.
1 |
<s:property value="#session.mySessionPropKey"/> |
or
1 |
<s:property value="#session['mySessionPropKey']"/> |
or
1 |
<s:property value="#request['myRequestPropKey']"/> |
The ActionContext is also exposed to Action classes via a static method, like below code:
1 |
ActionContext.getContext().getSession().put("mySessionPropKey", mySessionObject); |
Attributes which are not support dynamic content for them you can also put expressions, like below:
1 2 |
<c:set var="foo" value="bar" scope="request"/> <s:textfield name="username" label="%{#request.foo}" /> |