Struts 2 OGNL Expression Tutorial with Examples

OGNL is Object Graph Navigation Language. OGNL is an expression that can set and get the property of java object. In struts 2 OGNL is used to associate Action class and UI components. OGNL uses a standard naming convention to evaluate the Expression. OGNL is the root object for the value stack. In Struts 2 value stack is a set of several objects but OGNL looks value stack as a single object. OGNL expression can set and get values from application, session, value stack, action, request, parameters, and attr. 
Value stack is the root of OGNL. Action class resides in value stack so we directly fetch action class items using OGNL expression as

<s:property value="students"/>

  

But in case of session or request we need to use as below.

<s:property value="#session[‘sessionPropKey‘]"/>
<s:property value="#request[‘requestPropKey‘]"/>

  

In our struts 2 examples, we will deal with action class properties to

1. Fetch Array Using OGNL as <s:property value="students[0]"/> 
2. Fetch List Using OGNL as <s:property value="studentList[0]"/> 
3. Display Map Using OGNL as <s:property value="studentMap[‘A‘]"/> 
4. Use next level OGNL expression as <s:property value="college.name"/> 
5. Fetch action methods passing arguments Using OGNL as <s:property value="%{getSum(2,3)}" />

And display results on UI components. We are providing complete example to run the demo.

Download Source Code

struts-2-ognl-expression-tutorial-with-examples.zip

Find the eclipse structure of our example.

Display Array Using OGNL in Struts 2

Create an array in action class. Assign values in array. Create setter and getter methods for the defined property. 
UserActionOne.java

package com.concretepage.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import com.opensymphony.xwork2.ActionSupport;
@Namespace("/user")
@Action("/userOne")
@ResultPath(value="/")
@Result(name="success",location="userOne.jsp")
public class UserActionOne extends ActionSupport{
	private  String[] students = {"Ramesh","Mahesh","Dinesh"};
	public String execute() {
	   return SUCCESS;
	}
	public String[] getStudents() {
		return students;
	}
	public void setStudents(String[] students) {
		this.students = students;
	}
}

  

In JSP we can fetch array values as below using OGNL expression. 
userOne.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><title>Struts 2 OGNL Example</title>
</head>
<body>
<h3> Struts 2 Array OGNL Example </h3>

<br/><b>students: </b><s:property value="students"/>
<br/><b>students.length:</b> <s:property value="students.length"/>
<br/><b>students[0]:</b> <s:property value="students[0]"/>
<br/><b>students[1]:</b> <s:property value="students[1]"/>
<br/><b>students[2]:</b> <s:property value="students[2]"/>
<br/><b>top.students: </b><s:property value="top.students"/>

</body>
</html> </pre>

  

Use the link http://localhost:8080/Struts2Demo-1/user/userOne to see the output.

Display List Using OGNL in Struts 2

To work with list, create a list property in action class. Assign some values to the list and provide setter and getter methods. 
UserActionTwo.java

package com.concretepage.action;
import java.util.Arrays;
import java.util.List;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import com.opensymphony.xwork2.ActionSupport;
@Namespace("/user")
@Action("/userTwo")
@ResultPath(value="/")
@Result(name="success",location="userTwo.jsp")
public class UserActionTwo extends ActionSupport{
	private  List<String> studentList = Arrays.asList("Ramesh","Mahesh","Dinesh");
	public String execute() {
	   return SUCCESS;
	}
	public List getStudentList() {
		return studentList;
	}
	public void setStudentList(List studentList) {
		this.studentList = studentList;
	}
}

  

In JSP, list can be fetched in the same way as array using OGNL expression. 
userTwo.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><title>Struts 2 OGNL Example</title>
</head>
<body>
<h3>Struts 2 List OGNL Example</h3>

<br/><b>studentList: </b><s:property value="studentList"/>
<br/><b>studentList.size():</b> <s:property value="studentList.size()"/>
<br/><b>studentList[0]:</b> <s:property value="studentList[0]"/>
<br/><b>studentList[1]:</b> <s:property value="studentList[1]"/>
<br/><b>studentList[2]:</b> <s:property value="studentList[2]"/>
<br/><b>top.studentList: </b><s:property value="top.studentList"/>

</body>
</html>

  

Use the link http://localhost:8080/Struts2Demo-1/user/userTwo to see the output.

Display Map Using OGNL in Struts 2

In the same way we can access map using OGNL. Create a map and assign values in action class. And provide setter and getter methods. 
UserActionThree.java

package com.concretepage.action;
import java.util.HashMap;
import java.util.Map;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import com.opensymphony.xwork2.ActionSupport;
@Namespace("/user")
@Action("/userThree")
@ResultPath(value="/")
@Result(name="success",location="userThree.jsp")
public class UserActionThree extends ActionSupport{
	private  Map<String,String> studentMap = new HashMap<String,String>();
	{
		studentMap.put("A","Ramesh");
		studentMap.put("B","Mahesh");
		studentMap.put("C","Dinesh");
	}
	public String execute() {
	   return SUCCESS;
	}
	public Map<string, string=""> getStudentMap() {
		return studentMap;
	}
	public void setStudentMap(Map<string, string=""> studentMap) {
		this.studentMap = studentMap;
	}
}

  

In JSP use OGNL expression to fetch map with the key as usually we do in java. 
userThree.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><title>Struts 2 OGNL Example</title>
</head>
<body>
<h3>Struts 2 Map OGNL Example</h3>

<br/><b>studentMap: </b><s:property value="studentMap"/>
<br/><b>studentMap.size():</b> <s:property value="studentMap.size()"/>
<br/><b>studentMap[‘A‘]:</b> <s:property value="studentMap[‘A‘]"/>
<br/><b>studentMap[‘B‘]:</b> <s:property value="studentMap[‘B‘]"/>
<br/><b>studentMap[‘C‘]:</b> <s:property value="studentMap[‘C‘]"/>
<br/><b>top.studentMap: </b><s:property value="top.studentMap"/>

</body>
</html>

  

Use link http://localhost:8080/Struts2Demo-1/user/userThree to see output.

Use Next Level OGNL in Struts 2

To use next level OGNL expression, we are introducing a user bean College where we define id and name. 
College.java

package com.concretepage.vo;
public class College {
	private int id;
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

  

Use the college bean in action class and set some values. Define corresponding setter and getter method. 
UserActionFour.java

package com.concretepage.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import com.concretepage.vo.College;
import com.opensymphony.xwork2.ActionSupport;
@Namespace("/user")
@Action("/userFour")
@ResultPath(value="/")
@Result(name="success",location="userFour.jsp")
public class UserActionFour extends ActionSupport{
    private College college = new College();
    {
    	college.setId(10);
    	college.setName("UP College");
    }
    public String execute() {
	return SUCCESS;
    }
    public College getCollege() {
	return college;
    }
    public void setCollege(College college) {
	this.college = college;
    }
}

  

In JSP use next level OGNL expression to evaluate the values. 
userFour.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><title>Struts 2 OGNL Example</title>
</head>
<body>
<h3> Struts 2 Next Level OGNL Example </h3>

<br/><b>college.id: </b><s:property value="college.id"/>
<br/><b>college.name:</b> <s:property value="college.name"/>
<br/><b>college.name.length():</b> <s:property value="college.name.length()"/>

</body>
</html>

  

Fetch Action Methods Passing Arguments Using OGNL in Struts 2

In this example we will deal with action class methods for OGNL expression to evaluate methods. Methods can be two types, one that will not accept any arguments and second one that accepts arguments. In the action class we have taken both type of methods. 
UserActionFive.java

package com.concretepage.action;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import com.opensymphony.xwork2.ActionSupport;
@Namespace("/user")
@Action("/userFive")
@ResultPath(value="/")
@Result(name="success",location="userFive.jsp")
public class UserActionFive extends ActionSupport{
  	public String execute() {
	   return SUCCESS;
	}
	public String getMsg(){
		return "Hello World!";
	}
	public int getSum(int a, int b){
		return a+b;
	}
}

  

In JSP OGNL framework uses different approaches to fetch methods. Keep attention on JSP code how to fetch these two different methods. 
userFive.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><title>Struts 2 OGNL Example</title>
</head>
<body>
<h3> Struts 2 Method OGNL Example </h3>

<br/><b>getMsg(): </b><s:property value="msg"/>
<br/><b>getSum(a,b): </b><s:property value="%{getSum(2,3)}" />

</body>
</html>

  

Use the link http://localhost:8080/Struts2Demo-1/user/userFive to check the output.

Download Source Code

struts-2-ognl-expression-tutorial-with-examples.zip

时间: 2025-01-02 03:02:11

Struts 2 OGNL Expression Tutorial with Examples的相关文章

Struts 2 OGNL 对象访问

在Struts 2应用中,视图页面可以通过标签直接访问Action的属性(实际上这是一种假象,类似于Web应用保持application.session.request.page这4个范围的“银行”一样,Struts自行维护一个特定范围的“银行”,Action将数据放入其中,而JSP页面可以从其中取出数据,表面上似乎JSP可以直接访问Action数据),当Action属性不是简单值(基本数据类型或String类型)时,而是某个对象甚至是数组,集合时,就需要使用表达式语言来访问这些对象.数组.集合

struts与ognl结合

-----------------------------ognl表达式------------------------ OGNL:对象视图导航语言.  ${user.addr.name} 这种写法就叫对象视图导航.OGNL不仅仅可以视图导航.支持比EL表达式更加丰富的功能. 1.使用OGNL准备工作 1.1 导包 struts2 的包中已经包含了.所以不需要导入额外的jar包 1.2 代码准备 1.3 语法 1.3.1 基本取值 1.3.2 复值 1.3.3 调用方法 1.3.4 调用静态方法

struts基于ognl的自动类型转换需要注意的地方

好吧,坎坷的过程我就不说了,直接上结论: 在struts2中使用基于ognl的自动类型转换时,Action中的对象属性必须同时添加get/set方法. 例如: 客户端表单: <s:form action="registPro"> <s:textfield name="user.id" label="id"/> <s:textfield name="user.name" label="用户

struts的ognl.NoConversionPossible错误

JSP页面便利集合的时候,代码如下 <s:iterator value="storageList" id="stList" status="st"> <tr> <td class="list_data_number"><s:property value="#st.index+1"/></td> <td class="list_dat

Struts中OGNL的一些基本知识(#,${}等)

OGNL的概念: OGNL是Object-Graph Navigation Language的缩写,全称为对象图导航语言,是一种功能强大的表达式语言,它通过简单一致的语法,可以任意存取对象的属性或者调用对象的方法,能够遍历整个对象的结构图,实现对象属性类型的转换等功能. OGNL上下文实际上就是一个Map对象,由ognl.OgnlContext类表示.它里面可以存放很多个JavaBean对象. 原文地址:http://www.cnblogs.com/xly1208/archive/2011/11

MyBatis中的OGNL expression

当在项目运行的时候,出现这种异常,你就要去检查你的sql语句了. 比如以下:就会出现这种错误. 还有就是这种,assignTime是一个DATETIME类型的,这里却写( assignTIme != '' )这样也会出现以上错误.还有Integer也是一样的.

OGNL in Struts2 Tutorial

OGNL(Object-Graph Navigation language) is an expression language inherited by Struts from WebWork. Use of OGNL OGNL is used in struts to access model objects from a jsp page. It can be used to bind GUI elements to model objects in struts framework. I

(转载)SQL Reporting Services (Expression Examples)

https://msdn.microsoft.com/en-us/library/ms157328(v=SQL.100).aspx Expressions are used frequently in reports to control content and report appearance. Expressions are written in Microsoft Visual Basic, and can use built-in functions, custom code, glo

OGNL表达式的基本语法和用法------2

OGNL表达式的基本语法和用法 首先我们一起来看一下OGNL中的#.%和$符号.关于OGNL各种用法总结参看:http://blog.163.com/[email protected]/blog/static/72069304201032081730286/ 一.OGNL中的#.%和$符号 #.%和$符号在OGNL表达式中经常出现,而这三种符号也是开发者不容易掌握和理解的部分.在这里我们简单介绍它们的相应用途. 1.#符号的三种用法 1)访问非根对象属性,例如示例中的#session.msg表达