Expression language

Mondo Technology Updated on 2024-02-12

Simplify software maintenance for JSP applications by avoiding the use of scripting elements.

J**Aserver Pages (JSP) is a standard presentation layer technology used for the J2EE platform. JSP technology provides scripting elements and operations for performing calculations that dynamically generate page content. The scripting element allows you to include program sources in a JSP page, which can be executed when the page is rendered in response to a user request. Actions encapsulate computation operations into markup much like HTML or XML markup, which are typically included in the template text of a JSP page. The JSP specification defines only a few operations as standard, but from JSP 11 Starting with, developers have been able to create their own actions in the form of custom markup libraries.

The JSP Standard Markup Library (JSTL) is JSP 12 Custom set of tag libraries that implement basic functionality commonly used by a large number of server-side j**a applications. By providing a standard implementation for typical presentation layer tasks such as data formatting and iteration or conditional content, JSTL allows JSP authors to focus on application-specific development needs, rather than "starting anew" for these general-purpose operations.

Of course, you can use JSP scripting elements (scriptlets, expressions, and declarations) to achieve such tasks. For example, conditional content can be implemented using three scriptlets, which are highlighted in Listing 1. However, because scripting elements rely on embedding program sources (usually j**a) in the page, the complexity of the software maintenance task for JSP pages that use these scripting elements is greatly increased. For example, the scriptlet example in Listing 1 relies strictly on the correct matching of curly braces. If a syntax error is inadvertently introduced, nesting other scriptlets in conditional content can wreak havoc, and it can be difficult to make sense of the resulting error message when the JSP container compiles the page.

Listing 1Implement conditional content via scriptlets.

<% if (user.getrole() == "member")) else %
Fixing such problems usually requires considerable programming experience. While JSPs are usually developed and maintained by designers who are well-versed in page layout and graphic design, programmers are required to intervene when there is a problem with the scripting elements of the same page. This situation spreads the responsibility for a single file among multiple people, making developing, debugging, and enhancing such JSP pages a cumbersome task. By wrapping commonly used functionality into a standard collection of custom markup libraries, JSTL enables JSP authors to reduce the need for scripting elements, or even eliminate them, and avoid the associated maintenance costs.

jstl 1.0 was released in June 2002 and consists of four custom markup libraries (coreformatxmlwithsql) and a pair of generic tag library validators (scriptfreetlvwithpermittedtaglibstlvComposition. coreThe tag library provides custom actions, manages data with scoped variables, and performs iteration and conditional manipulation of page content. It also provides markup for generating and manipulating URLs. As the name suggests,formatThe tag library defines the operations used to format data, especially numbers and dates. It also supports the internationalization of JSP pages using localized resource bundles. xmlThe library contains tags that are used to manipulate data represented by XMLsqlThe library defines the operations that are used to query the relational database.

Two JSTL markup library validators allow developers to enforce the use of coding standards in their JSP applications. Can be configuredscriptfreetlvValidator to disable various types of JSP script elements scriptlets, expressions, and declarations in JSP pages. Similarly,permittedtaglibstlvValidators can be used to limit the set of custom markup libraries (including JSTL markup libraries) that may be accessed by an application's JSP pages.

Although JSTL will eventually become a required component of the J2EE platform, only a handful of application servers currently include it. jstl 1.A reference implementation of 0 is available as part of the Apache Software Foundation's Jakarta Taglibs project (see Related topics). You can incorporate a custom markup library from that reference implementation into any support for JSP 12 and servlet 23 Spec Server to add support for JSTL.

In JSP 12, you can use static strings or expressions (if allowed) to specify the properties of a JSP operation. For example, in Listing 2, rightOperationalnamewithpropertyThe property specifies a static value, while it specifies it with an expressionvalueAttribute. The effect of this is to assign the current value of the request parameter to the named bean attribute. Expressions used in this form are called request-time attribute values, and this is the only mechanism built into the JSP specification for dynamically specifying attribute values.

Listing 2JSP operation of the property value at the time of the merge request.

Because request-time property values are specified by expressions, they often suffer from the same software maintenance issues as other script elements. As a result, JSTL custom markup supports another mechanism for specifying dynamic property values. You can specify the property values of a JSTL operation using a simplified Expression Language (EL) instead of a full JSP expression. EL provides identifiers, accessors, and operators for retrieving and manipulating data residing in JSP containers. EL is somewhat based on ECMASCRIPT (see Related topics) and XML Path Language (XPATH), so page designers and programmers alike should be familiar with its syntax. el excels at finding objects and their properties, and then performing simple operations on them; It's not a programming language, or even a scripting language. However, when used with JSTL markup, it can be used to represent complex behaviors using simple and convenient symbols. The format of the el expression is as follows: delimited by a dollar sign ($) and included in curly braces ({}, as shown in Listing 3.

Listing 3Describes the JSTL operation of the EL expression delimiter.

In addition, you can combine multiple expressions with static text to construct dynamic property values through string juxtaposition, as shown in Listing 4. A separate expression consists of an identifier, an accessor, a literal, and an operator. An identifier is used to refer to a data object that is stored in a data center. EL has 11 reserved identifiers, corresponding to 11 EL implicit objects. Suppose all other identifiers refer to a variable that limits the scope . An accessor is used to retrieve the properties of an object or the elements of a collection. Literals represent fixed values such as numbers, characters, strings, booleans, or null values. Operators allow data and text to be combined and compared.

Listing 4Combine static text and multiple EL expressions to specify dynamic attribute values.

JSP API passedActions allow data to be stored and retrieved from four different scopes within a JSP container. JSTL extends this capability by providing additional operations for specifying and removing objects in these scopes. In addition, EL provides built-in support for retrieving these objects as scope-constrained variables. In particular, any identifier that appears in an EL expression but does not correspond to any EL implicit object is automatically assumed to be referencing an object stored in one of the four JSP scopes, which are:

Page ScopeRequest ScopeSession ScopeApplication ScopeYou may recall that objects stored in that page scope can only be retrieved during the processing of a page for that request. If objects are stored in the scope of a request, they can be retrieved during the processing of all the pages involved in the processing of a request (for example, one or more encountered in the processing of a request).oraction). If an object is stored in the session scope, it can be retrieved by any page that the user visits (that is, until it is associated with that user interaction) during an interactive session with the web applicationhttpsessionobject is invalid). Objects stored in the application scope can be accessed by any user from any page until the web application itself is uninstalled (usually due to closing the JSP container).

Store objects to the scope by mapping strings to objects in that scope. You can then retrieve the object from that scope by providing the same string. Looks up the string in the mapping of the scope and returns the object that is mapped. In the Servlet API, such objects are referred to as properties of the corresponding scope. However, in the context of EL, the string associated with the property is also considered to be the name of the variable, which obtains a specific value by means of property mapping.

In EL, identifiers that are not associated with implicit objects are considered name objects stored in the four JSP scopes. Check for such an identifier first for the page scope, then for the request scope, then for the session scope, then for the application scope, and then test for whether the name of the identifier matches the name of an object stored in that scope. The first such match is returned as the value of the el identifier. In this way, you can think of the EL identifier as a reference to a variable that limits the scope.

On a more technical level, there is no identifier mapped to an implicit object that is usedpagecontextinstancefindattribute()method evaluation, which represents the processing of a page on which the expression for the request is currently being processed. The name of the identifier is passed as a parameter to the method, which then searches for properties with the same name in each of the four scopes. and take the first match found asfindattribute()The value of the method is returned. If no such property is found in these four scopes, it is returnednull

Ultimately, the variable that limits the scope is the properties of the four JSP scopes that have names that can be used as EL identifiers. As long as you give alphanumeric names to variables that are scoped to them, you can create them through any of the mechanisms available in JSP for setting properties. This includes built-in onesoperations, as well as those defined by several classes in the Servlet APIsetattribute()Method. In addition, many of the custom tags defined in the four JSTL libraries are natively capable of setting property values that are used as scoped variables.

The identifiers for 11 EL implicit objects are listed in Table 1. These objects are not to be confused with JSP implicit objects (there are only nine in total), only one of which is common to them.

Table 1el implicit objects.

Category identifier and description jspPageContext: The PageContext instance corresponds to the processing of the current page. Scoped Pagescope: The map class associated with the name and value of the page-scoped property. RequestScope: The MAP class associated with the name and value of the request-scoped property. SessionScope: The map class associated with the name and value of the session scope property. Applicationscope: The map class associated with the name and value of the application's scope property. Request parameter param: A map class that stores the primary value of the request parameter by name. paramvalues: A map class that stores all the values of the request parameters as a string array. Request header: A map class that stores the main value of the request header by name. HeaderValues: A map class that stores all the values of the request header as a string array. cookiecookie: A map class that stores the cookie attached to the request by name. Initialization parameter initparam: A map class that stores the initialization parameters of the web application context by name.

jsppagecontext pagecontextThe instance corresponds to the processing scope of the current pagepagescopeThe name and value associated with the page scope propertymapclassrequestscopeThe name and value associated with the request scope propertymapclasssessionscopeThe name and value associated with the session scope propertymapclassapplicationscopeAssociated with the name and value of the application's scoped propertymapClass request parametersparamStores the main value of the request parameter by namemapclassparamvaluesTreat all the values of the request parameters asstringarraymapClass request headerheaderStores the primary value of the request header by namemapclassheadervaluesTreat all the values of the request header asstringarraymapClass cookiescookieBy name the storage request of the cookiemapClass initialization parametersinitparamStores the Web Application Context Initialization parameter by namemapclass

Although there is only one public object (in JSP and EL implicit objectspagecontext), but other JSP implicit objects can also be accessed through EL. The reason ispagecontextFeatures that access all eight other JSP implicit objects. In fact, this is the main reason for including it in el implicit objects.

All the remaining el implicit objects are mappings that can be used to find objects that correspond to names. The first four mappings represent the various attribute scopes discussed earlier. You can use them to find identifiers in a specific scope, rather than relying on the sequential lookup process that EL uses by default.

The next four mappings are used to get the values of the request parameters and the request header. Because the HTTP protocol allows multiple values for request parameters and request headers, they each have a pair of mappings. The first mapping in each pair returns the primary value of the request parameter or header, usually the value that happens to be specified first in the actual request. The second mapping in each pair allows all values of a parameter or header to be retrieved. The keys in these mappings are the names of the parameters or headers, but these values arestringAn array of objects, where each element is a single parameter value or header value.

The cookie implicit object provides access to the name of the cookie set by the request. This object maps all the cookie names associated with the request to the ones that represent those cookiescookieObject.

The last el implicit objectinitparamis a map that stores the names and values of initialization parameters for all the contexts associated with a web application. The initialization parameter is passedweb.xmlThe deployment descriptor file is located in the applicationweb-infTable of Contents.

Because el identifiers are resolved as implicit objects or scoped variables (via attributes), it is necessary to convert them to j**a objects. EL can automatically wrap and unwrap its base type in its corresponding J**a class (e.g., you can set it in the backgroundintCast tointegerclass, or vice versa), but most of the identifiers will be pointers to the full j**a object.

As a result, the properties of these objects or (in the case of objects being arrays and collections) access to their elements are generally satisfactory. To accomplish this, EL provides two different accessors (the point operator () and the square bracket operator (It is also supported to manipulate properties and elements through EL.

Point operators are typically used to access the properties of an object. For example, in expressionson your Mac, use the dot operator to access ituserThe name of the object to which the identifier refersfirstnamecharacteristics. EL uses the j**a bean convention to access an object property, so you must define a getter method for this property (usually namedgetfirstname()so that the expression evaluates correctly. When the property being accessed is itself an object, the point operator can be applied recursively. For example, if we make up somethinguserThe object has an implementation of a j**a objectaddressproperties, then you can also use the dot operator to access the properties of this object. For example, expressionsThis address object nested will be returnedcityCharacteristic.

The square bracket operator is used to retrieve elements of arrays and collections. In arrays and ordered sets (i.e., implementedj**a.util.listinterface), put the subscript of the element to be retrieved in square brackets. For example, expressionsReturnurlsThe identifier refers to the fourth element of an array or collection (as in the J**a language and J**Ascript, the subscript in EL starts from zero).

For implementationj**a.util.mapA collection of interfaces, the square bracket operator uses the associated key to find the value stored in the map. Specify the key in square brackets and return the corresponding value as the value of the expression. For example, expressionsBack withcommandsidentifiermap"dir"The value associated with the key.

In both cases, you can allow expressions to appear in square brackets. The result of evaluating a nested expression will be used as a subscript or key to retrieve the appropriate element of the collection or array. Like the dot operator, the square bracket operator can be applied recursively. This enables EL to retrieve elements from multidimensional arrays, nested collections, or any combination of both. In addition, the dot operator and the bracket operator are interoperable. For example, if the elements of an array are themselves objects, you can use the bracket operator to retrieve the elements of the array, combined with the dot operator to retrieve one of the element's properties (for example

Assuming that EL acts as a simplified language for specifying dynamic property values, an interesting function of EL accessors (unlike j**a accessors) is that they are applied tonulldoes not throw an exception. If you apply an object to which the EL accessor is applied, for example,withfooidentifier) isnull, then the result of the application accessor is alsonull。This turns out to be quite a useful behavior in most cases, and it won't be long before you get to the point.

Finally, it is possible to achieve some degree of interchange between the dot and square bracket operators. For example, it can also be usedto retrieveuserobjectfirstnamefeatures, as can be usedGet withcommandsin the mapping"dir"The keys are associated with the same values.

EL can also traverse a hierarchy of objects that contain application data (exposed by scoped variables) or information about the environment (via EL implicit objects) by using identifiers and accessors. However, simply accessing this data is often not enough to implement the presentation logic required by many JSP applications.

Ultimately, EL also includes several operators that manipulate and compare the data accessed by the EL expression. These operators are summarized in Table 2.

Table 2el operator.

Category operators, arithmetic operatorsordivwithormodRelational operatorsoreqorneorltorgtorlewithorgeLogical operatorsorandororwithornot) verification operatorempty

Arithmetic operators support addition, subtraction, multiplication, and division of numeric values. A remainder operator is also provided. Note: Both the division and remainder operators have alternate, unsymbolic names (to be consistent with xpath). An example expression that demonstrates the use of arithmetic operators is shown in Listing 5. The result of applying an arithmetic operator to several EL expressions is the result of applying that arithmetic operator to the numeric values returned by those expressions.

Listing 5EL expressions that make use of arithmetic operators.

Relational operators allow you to compare numeric or textual data. The results of the comparison are returned as Booleans. Logical operators allow boolean values to be merged, returning new boolean values. As a result, you can apply the EL logical operator to the result of a nested relationship or logical operator, as shown in Listing 6.

Listing 6EL expressions that make use of relational and logical operators.

The last type of el operator isempty, which is especially useful for validating data. emptyThe operator takes a single expression as its variable (that is,), and returns a Boolean value that indicates whether the result of evaluating the expression is a "null" value. The result of the evaluation isnullThe expression is considered null, i.e., a collection or array without elements. If the parameter is for a length of zerostringThe result of the evaluation, thenemptyThe operator will also be returnedtrue

In el expressions, numbers, strings, booleans, andnullcan be specified as literal values. Strings can be delimited with single or double quotes. Boolean values are specified astruewithfalse

As we discussed earlier, JSTL 10 includes four custom marker libraries. To demonstrate the interaction between JSTL markup and expression language, we'll look at a couple of data from JSTLcoreTags for the library. As with any JSP custom markup library, it must be included in any page you want to use this library markuptaglibPseudo-directives. Listing 7 shows the pseudo-directives used for this particular library.

Listing 7Taglib pseudo-directive for the EL version of the JSTL Core library.

<%@taglib uri="" prefix="c" %>
Actually, corresponds to jstlcoreLibrarytaglibThere are two kinds of pseudo-directives, as in jstl 10, el is optional. All four JSTL 10 custom markup libraries have alternate versions that use JSP expressions instead of ELs to specify dynamic property values. Because these alternate libraries rely on JSP's more traditional request-time attribute values, they are called RT libraries, and those that use the expression language are called EL libraries. Developers use differenttaglibPseudo-directives to distinguish between these two versions of each library. Listing 8 shows a pseudo-directive using the RT version of the Core library. However, since the focus of our discussion is now on EL, these pseudo-directives are needed first.

Listing 8Taglib pseudo-directive for the RT version of the JSTL Core library.

<%@taglib uri="_rt" prefix="c_rt" %>
The first JSTL custom markup we want to consider is:action). As already explained, scoped variables play a key role in JSTLActions provide a tag-based mechanism to create and set scoped variables. The syntax for the operation is shown in Listing 9, where:varThe property specifies the name of the variable that is scopedscopeThe property indicates in which scope the variable residesvalueThe property specifies the value assigned to the variable. If the specified variable already exists, simply assign the specified value to it. If it doesn't exist, create a new scoped variable and initialize the variable with that value.

Listing 9Syntax for the operation.

scopeThe property is optional, and its default value ispage

It is shown in Listing 10Two examples. In the first example, set the session scope variable to:stringValue. In the second example, use an expression to set the value: name the page scopesquareThe variable is namedxThe square of the value of the request parameter.

Listing 10Example of operation.

You can also specify the value of a variable that has a limited scope asThe main content of the action, rather than using the property. With this approach, you can rewrite the first example in Listing 10, as shown in Listing 11. Moreover, as we can see right away,The body content of the tag itself can also be used with custom tags. All content generated within the body will be created as onestringA value is assigned to a specified variable.

Listing 11Specified by the body contentThe value of the operation.

cst
The JSTL Core library contains a second tag for managing variables that are scoped。As the name suggests,The action is used to remove a variable that has a limited scope, and it gets two properties. varattribute specifies the name of the variable to be deletedscopeThe attribute is optional, and it indicates the scope from which the variable to be deleted comes from, and the default ispageas shown in Listing 12.

Listing 12Example of operation.

AlthoughActions allow the expression result to be assigned to a variable that is scoped, but developers often want to display only the value of the expression and not store it. jstlCustom markup takes on this task and has the syntax shown in Listing 13. The tag pair is determined by itvalueThe expression specified by the property is evaluated, and the result is printed. If an optional attribute is specifieddefaultWell, in the rightvalueThe result of the evaluation of the expression of the attribute isnullor emptystringcase,Its value is printed.

Listing 13Syntax for the operation.

escapexmlAttributes are also optional. It controls when usedTag whether or not it should be escaped when outputting characters such as "<" and "&" which have special meaning in HTML and XML. If it willescapexmlSet to true, these characters are automatically converted to the corresponding XML entities (the characters mentioned here are converted to each otherwith

For example, suppose there is a file calleduser, which is an instance of a class that defines two properties for the user:usernamewithcompany。This object is automatically assigned to a session whenever a user visits the site, but both properties are not set until the user is actually logged in. Assuming this scenario, consider the JSP fragment in Listing 14. After the user logs in, the snippet will display the word "hello", followed by his or her username and an exclamation point. However, before the user logs in, the content generated by this snippet is the phrase "hello guest!".”。In this case, becauseusernameFeatures have yet to be initialized, soThe markup will be printed out insteaddefaultThe value of the property (i.e., the string "guest").

Listing 14with default contentExample of operation.

hello !
Next, consider Listing 15, which usesTaggedescapexmlAttribute. If in this case it has already beencompanyThe property is set to j**astringValue. "flynn & sons", then, in fact, what the operation generates will beflynn & sons。If this is part of a JSP page that generates HTML or XML content, then the "&" symbol in the middle of the string may end up being interpreted as an HTML or XML control character, preventing the display or parsing of that content. However, if you willescapexmlThe property value is set totrue, the generated content will beflynn & sons。Browsers or parsers don't have problems with this kind of content when interpreting. Let's assume that HTML and XML are the most common types of content in JSP applications, soescapexmlThe default value for the property istrueNot surprisingly.

Listing 15Disable escapingExample of operation.

In addition to simplifying the display of dynamic data, when passingWhen a variable value is setThe ability to specify a default value is also useful. As listed in Listing 11The value used to assign to a variable that limits the scope can be specified, as shown by the value of the Specify by Body Content actionThe body content of a tag, which can also be specified by its value property. By willingActions are nested intags, variable assignments can take advantage of their default value capabilities. This approach is illustrated in Listing 16. ExternalThe behavior of a tag is very simple: it sets the session scope based on its body contenttimezoneThe value of the variable. However, in this case, the main content is passedOperation-generated. The value property of this nested operation is an expression, it tries to passcookieThe implicit object returns a name namedtzprefcookie value. (cookieThe implicit object maps the cookie name to the corresponding onecookieinstance, which means that it must pass through the object'svalueFeatures use dot operators to retrieve the actual data stored in cookies. )

Listing 16Mergewithto provide a default variable value.

However, consider the following scenario where the user is trying to use this web application for the first time. As a result, there is no provision in the request for a name namedtzprefCookies. This means that lookups that use implicit objects will be returnednull, in which case the entire expression will be returnednull。Because yesTaggedvalueThe result of the property evaluation is:null, sotags are then output to themdefaultThe result of the evaluation of the property. In this case, the stringcst。Therefore, the actual result is that it willtimezoneScoped variables are set to usertzprefThe time zone stored in the cookie or, if not, the default time zonecst

el and jsp 20

Currently, the expression language can only be used to specify dynamic attribute values in jstl custom tags. But JSTL 1An extension of the 0 expression language has been proposed to include it in JSP 20 in the middle of the review, and the final review is currently underway. This extension will allow developers to use EL through their own custom markup. Page authors will be able to use EL expressions anywhere JSP expressions are currently allowed, such as inserting dynamic values into template text:

your preferred time zone is $
This jsp 2The 0 feature (like JSTL itself) will allow page authors to further reduce their reliance on JSP scripting elements, thereby improving the maintainability of JSP applications.

EL (combined with the operations provided by the four JSTL custom markup libraries) allows page authors to implement presentation layer logic without the use of script elements. For example, compare Listing 1 at the beginning of this articleThe scriptlets are used to implement the same functionality as JSP in conditional content and JSTL as shown in Listing 17. (jstlcoreThe rest of the tags in the library, including:and its sub-tags, which will be discussed in the next article in this series. Although conditional logic is obviously executed, there is no j.a. source in the JSTL version, and the relationships between markup (especially regarding nesting requirements) should be familiar to anyone who is proficient in HTML syntax. Listing 17Mergewithto provide a default variable value.

welcome, member!

welcome, guest!

By providing a standard implementation of features that are common to most web applications, JSTL helps accelerate development cycles. Combined with EL, JSTL eliminates the need to program the presentation layer, which greatly simplifies the maintenance of JSP applications.

Controlling JSP Pages with Custom MarkupJSP Markup Library: Designing for Better Usability JSP Standard Markup Library Home PageJakarta TaglibsJSTL in Action Control JSP Pages with Custom Markup.

Related Pages