Search from Struts2 Library

Monday, September 22, 2008

OGNL



Struts2 and OGNL
Throughout Struts 2 web applications, a need exists to link the Java runtime with the text-based world of HTML, HTTP, JSP, and other text-based view-rendering technologies. There must be a way for these text-based documents to reference runtime data objects in the Java environment. A common solution to this problem is the use of expression languages. As we’ve seen, Struts 2 uses OGNL for this purpose. We’ll now take the opportunity to cover the features of this expression language that you’ll most likely need to use in Struts 2 development.

What is OGNL?
The Object-Graph Navigation Language exists as a mature technology completely distinct from Struts 2. As such, it has purposes and features much larger than its use within Struts 2. OGNL is an expression and binding language. In Struts 2, we use the OGNL expression language to reference data properties in the Java environment, and we use OGNL type converters to manage the type conversion between HTTP string values and the typed Java values.
In this last section, we’ll try to summarize the syntax and some of the more useful features of the OGNL expression language. First we’ll cover the syntax and features most commonly used in Struts 2 development. Then we’ll cover some of the other OGNL features that you might find handy. OGNL has many of the features of a full programming language, so you’ll find that most everything is possible. Also note that this section doesn’t try to be a complete reference to OGNL. If you want more OGNL power, visit the website at www.ognl.org for more information.
Keep those JSPs clean! While OGNL has much of the power of a fullfeatured language, you might want to think twice before squeezing the trigger. It’s a well-established best practice that you should keep business logic out of your pages. If you find yourself reaching for the OGNL power tools, you might well be pulling business logic into your view layer. We’re not saying you can’t do it, but we recommend giving it a moment’s thought before complicating your view pages with too much code-style logic. If you’re getting complex in your OGNL, ask yourself if what you’re doing should be done in the action or, at least, encapsulated in a helper bean that you can use in your page.

No comments: