EL expression, EL expression

Source: Internet
Author: User

EL expression, EL expression
On the JSP 2.0 page, we use the following elements to call the expression language:
$ {Expression}
EL can appear in the template Text of the JSP page or in the attributes of the JSP tag.
The following expressions are used in JSP template text:
<Ul>
<Li> customer NAME: $ {customer. custName}
<Li> Email address: $ {customer. email}
</Ul>
The EL expression is used in JSP standard Action attributes as follows:
<Jsp: include page = "$ {expression1}"/>
<C: out value = "$ {expression2}"/>

Functions of Expression Language

(1) provides a set of simple operators. Expression Language provides a set of simple and effective operators that can be used to check arithmetic, relational, logical, conditional, or null values.
(2) convenient access to scope variables. Scope variables are objects stored in the PageContext, HttpServletRequest, HttpSession, or ServletContext scope using the setAttribute () method. They can be accessed in the following way:
$ {UserName}

(3) A simple representation of Access to the JavaBeans object. To access the custName attribute of a JavaBean object customer on the JSP page, the following syntax is required:
<Jsp: getProperty name = "customer" property = "custName">
The EL expression can be used as follows:
$ {Customer. custName}
(4) simple access to the collection elements. The collection includes arrays, List objects, and Map objects. The following simple form can be used to access the elements of these objects:
$ {Variable [indexOrKey]}

(5) simple access to request parameters, cookies, and other request data. To access the Accept request header, you can use the header implicit variable as follows:
$ {Header. Accept} or $ {header ["Accept"]}
(6) provides the function of using Java functions in EL. EL cannot define and use variables or call object methods, but Java functions can be used as labels.

Differences between EL expressions and JSP:

The format of JSP expressions is:
<% = Expression %>
The expression here is a valid Java expression, which belongs to the script language code. Variables declared by scripts can be used in expression.
The EL expression format is:
$ {Expression}
The expression here is an expression that complies with EL specifications and does not need to be included in the tag. The EL expression cannot use variables declared in the script.

With the traditional scripting language, it is easy to declare variables in JSP. The label used is <%! And %>, for example:
<%! Int count = 100; %>
An integer variable is declared here, and then the following JSP expression statement is used. The output variable count value is 100:
The count value is: <% = count %>
If the following statement is used, a null value is returned, that is, the empty operator of EL is used to test the result as true.
The count value is :$ {count}
In EL, variables cannot be defined or declared in scripts. However, it can access request parameters, scope variables, JavaBeans, and EL implicit variables.

E Arithmetic Operator:

Arithmetic Operators
+ Add ${6.80 +-12}-5.2
-Minus $ {15-5} 10
* Multiply $ {2*3.14159} 6.28318
/Or div except ${25 div 5} and $ {25/5} 5.0
% Or mod get remaining ${24 mod 5} and $ {24% 5} 4

In EL expressions, "e" can also be used to represent power operations in floating point numbers. For example:
The result of $ {1.5e6/1000000} is 1.5;
The result of $ {1e6*1} is 1000000.0.
These operations call methods in the class during execution, but pay attention to the Data Type of the operation results. For example, the calculation result of the fixed point and floating point is always a floating point value. Similarly, low-Precision values and high-precision values are computed. For example, when an Integer value is added to a BigInteger value, a high-precision value is always obtained.
Like a value, arithmetic operators can also be used on a String object, as long as the String object can be converted to a value. For example:
The result of $ {"16" * 4} is 64, and the string is converted to an integer of 16;

The result of $ {a div 4} is 0.0. a is not defined. Its default value is 0;
$ {"A" div 4} produces a compilation error. The string "a" cannot be computed with a value.
Relational operators
= Or equal eq ${3 = 5} or ${3 eq 5} false
! = Or ne is not equal $ {3! = 5} or ${3 ne 5} true
<Or lt less than ${3 <5} or ${3 lt 5} true
> Or gt is greater than $ {3> 5} or ${3 gt 5} false
<= Or le is less than or equal to ${3 <= 5} or ${3 le 5} true
>=Or ge is greater than or equal to ${3 >=5} or ${3 ge 5} false

Java flow control statements, such as if, for, and while, are not allowed in EL. Therefore, logical expressions are used to directly display the boolean values of expressions.

The syntax of EL's conditional operators is:
Expression? Expression1: expression2
The expression value is based on the expression value, which is a boolean expression. If expression is true, the result of expression1 is returned. If expression is false, the result of expression2 is returned. For example:
$ {(5*5) = 25? The result of 1: 0} is 1;
${(3 gt 2 )&&! (12 gt 6 )? "Right": "Wrong"} returns Wrong;
$ {("14" eq 14.0) & (14 le 16 )? "Yes": "No"} returns Yes;
${(4.0 ne 4) | (100 <= 10 )? The result of 1: 0} is 0.

Empty operator format:
$ {Empty expression}
It determines whether the expression value is null, an empty string, an empty array, an empty Map, or an empty set. If so, true is returned; otherwise, false is returned.

Access operators for attributes and geometric elements

Attribute access operators are used to access object members, and set access operators are used to retrieve elements of Map, List, or array objects. These operators are particularly useful when processing implicit variables. In EL, these operators have the following two types:
• Period (.) operator.
• Square brackets ([]) operator.

1. Dot (.) Operator
The dot operator is used to access the value of a key of the Map object or the attribute value of the bean object. For example, param is an implicit object of EL and is a Map object, the following code returns the value of the Request Parameter of the param object username:
$ {Param. username}
For example, if customer is an instance of the CustomerBean class, the following code accesses the custName attribute value of the instance:
$ {Customer. custName}

2. square brackets ([]) Operator
In addition to accessing the Map object key value and bean attribute value, the square brackets operator can also access the elements of List objects and array objects. For example:
$ {Param ["username"]} or $ {param ['username']}
$ {Customer ["custName"]}

Access scope variable:

On the JSP page, you can use JSP expressions to access scope variables.
The general practice is to use the setAttribute () method in Servlet to store a variable to a specific scope object, such as HttpServletRequest, HttpSession, and ServletContext. Then, use the forward () method of the RequestDispatcher object to forward the request to the JSP page. On the JSP page, call the getAttribute () method of the implicit variable to return the value of the scope variable.
With EL, you can easily access these scope variables. To output the value of the scope variable, you only need to use the variable name in EL. For example:
$ {Variable_name}
For this expression, the container searches for the attributes named variable_name in the page scope, request scope, session scope, and application scope. If this attribute is found, its toString () method is called and the property value is returned. If no value is found, an empty string (not null) is returned ).
Access JavaaBean attributes:

There is a JavaBeans named com. model. mermerbean, which has an attribute named custName. To access the custName attribute on the JSP page, use the following code:
<% @ Page import = "com. model. CustomerBean" %>
<%
CustomerBean customer = (CustomerBean) pageContext. findAttribute ("customer ");
Customer. setCustName ("Hacker ");
%>
<% = Customer. getCustName () %>
The findattriname () method of pageContext is used to find the property named customer and output the value of custName using a JSP expression. However, if the specified property cannot be found, the above Code will throw an NullPointerException.

If you know the full name of the JavaBeans and its scope, you can also use the following JSP standard action to access the attributes of the JavaBeans:
<Jsp: useBean id = "customer" class = "com. model. CustomerBean"
Scope = "session"/>
<Jsp: setProperty name = "customer" property = "custName" value = "Hacker"/>
<Jsp: getProperty name = "customer" property = "custName"/>

If you use the expression language, you can easily access the attributes of JavaBeans through the dot notation, as shown below:
$ {Customer. custName}
When expression language is used, if the specified attribute is not found, no exception is thrown, but an empty string is returned.

Expressions allow access to nested attributes. For example, if CustomerBean has an address attribute whose type is AddressBean and AddressBean has the zipCode attribute, you can access the zipCode attribute in the following simple form:
${Mer.address.zip Code}
The preceding method cannot be implemented using <jsp: useBean> or <jsp: getProperty>.
The following example shows the access to the JavaBeans attribute. In this example, there are two JavaBeans, respectively AddressBean, which has three string types of attributes, city, street and zipCode; customerBean adds an attribute address of the AddressBean type based on the preceding class.

In CustomerServlet. the java program creates a CustomerBean object and sets it as an attribute of the Request scope. Then, the request is forwarded to the JSP page, on the JSP page, use the following EL to access the three attributes of the customer address:
<Li> city :$ {customer. address. city}
<Li> street :$ {customer. address. street}
<Li> zipCode: $ {customer.address.zip Code}

Element of the access set:

In EL, you can access the elements of various set objects. a set can be an array, List object, or Map object. This requires the array notation operator ([]). For example, if there is an attributeName object of the above type, you can access its elements in the following form:
$ {AttributeName [entryName]}


If the attributeName object is an array, entryName is a subscript. The above expression returns the element value of the specified base object.

(1) The following Code demonstrates the access to array elements:
<%
String [] favoriteFruit = {"apple", "orange", "banana "};
Request. setAttribute ("favoriteList", favoriteFruit );
%>
My favorite fruit is :$ {favoriteList [2]}
The preceding line can also be written as follows:
My favorite fruit is :$ {favoriteList ["2"]}

(2) If the attributeName object is an object that implements the List interface, entryName is an index.
The following code demonstrates the access List element:
<% @ Page import = "java. util. ArrayList" %>
<%
ArrayList <String> favoriteFruit = new ArrayList <String> ();
FavoriteFruit. add ("apple ");
FavoriteFruit. add ("orange ");
FavoriteFruit. add ("banana ");
Request. setAttribute ("favoriteList", favoriteFruit );
%>
My favorite fruit is :$ {favoriteList [2]}

(3) If the attributeName object is an object that implements the Map interface, entryName is the key and the corresponding value is obtained through the get (key) method of the Map object. For example:
<% @ Page import = "java. util .*"
ContentType = "text/html; charset = gb2312" %>
<%
Map <String, String> capital = new HashMap <String, String> ();
Capital. put ("England", "London ");
Capital. put ("China", "Beijing ");
Capital. put ("Russia", "Moscow ");
Request. setAttribute ("capital", capital );
%>
The capital of China is: $ {capital ["China"]}
The capital of Russia is :$ {capital. Russia}

Access the hidden variables in EL:

On the JSP page, you can access JSP implicit variables, such as request, session, and application. An EL expression also defines a set of its own hidden variables. Using EL, you can directly access these hidden variables.

1. pageContext variable
PageContext is a variable of the PageContext type. The PageContext class has the attributes request, response, session, out, And servletContext in sequence. You can use the pageContext variable to access the attributes of these attributes.
The following are some examples:

$ {PageContext. request. method} // method used to obtain an HTTP request, such as GET or POST.
$ {PageContext. request. queryString} // query string for the request
$ {PageContext. request. requestURL} // obtain the request URL
$ {PageContext. request. remoteAddr} // obtain the requested IP Address
$ {PageContext. session. id} // obtain the session ID
$ {PageContext. session. new} // checks whether the session object is created.
$ {PageContext. servletContext. serverInfo} // obtain server information
The preceding EL is the attribute of the object accessed through the member access operator. The method of the object cannot be called in EL, so the following usage is incorrect:
$ {PageContext. request. getMethod ()}
However, you can still use the following script expression:
<% = Request. getMethod () %>
2. param and paramValues Variables
The param and paramValues variables are used to retrieve request parameter values from ServletRequest. The param variable is the result of calling the getParameter (String name) method of the given parameter name. EL is used to indicate the following:
$ {Param. name}
Similarly, paramValues returns an array of parameter values of a given name using the getParameterValues (String name) method. To access the first element of the parameter value array, use the following code:
$ {ParamValues. name [0]}
The above code can also be expressed in the following two forms:
$ {ParamValues. name ["0"]}
$ {ParamValues. name ['0']}

Because the array elements are accessed by an integer subscript, you must use the [] operator to access the array elements. The following two expressions generate compilation errors:
$ {ParamValues. name.0}
$ {ParamValues. name. "0 "}
Therefore, EL's access to attributes and sets is not exactly the same as the traditional Java syntax.

3. header and headerValues Variables
The header and headerValues variables retrieve values from the HTTP request header. Their operating mechanism is similar to param and paramValues. The following code uses EL to display the host value of the request header.
$ {Header. host} or $ {header ["host"]}
Similarly, headerValues. host is an array. Its first element can be displayed using one of the following expressions:
$ {HeaderValues. host [0]}
$ {HeaderValues. host ["0"]}
$ {HeaderValues. host ['0']}
4. cookie variables
The following code can be used to send a Cookie to the client in Servlet:
Cookie cookie = new Cookie ("userName", "Hacker ");
Response. addCookie (cookie );
To retrieve the Cookie sent from the client to the server, use the following code:
Cookie [] cookies = request. getCookies ();
For (int I = 0; I <cookies. length; I ++ ){
If (cookies [I]. getName (). equals ("userName ")){
Out. println (cookies [I]. getValue ());
}
}
On the JSP page, you can use the cookie implicit variable of EL to obtain the Cookie array sent back from the client to the server, that is, the returned result of calling the getCookies () method of the request object. If you want to access the cookie value, you need to use the attribute value (that is, the getValue method) of the Cookie class ). Therefore, the following line can output the Cookie value named userName. If this cookie object is not found, an empty string is output:
$ {Cookie. userName. value}
You can also use the cookie variable to access the session Cookie ID value, for example:
$ {Cookie. JSESSIONID. value}

5. initParam variable
The initParam variable stores the parameter names and parameter values of the Servlet context. For example, the following initialization parameters are defined in DD:
<Context-param>
<Param-name> email </param-name>
<Param-value> hacker@163.com </param-value>
</Context-param>
You can use the following EL expression to obtain the parameter email value:
$ {InitParam. email}
If you access the Servlet context parameter through a JSP script element, use the following expression:
<% = Application. getInitParameter ("email") %>

6. pagination, requestScope, sessionScope, and applicationScope Variables
These hidden variables are easy to understand. They are used to restrict access to attributes of different scopes. For example, the following code adds a totalPrice attribute indicating the commodity price in the session scope, and then uses EL to access the attribute value:
<%
Session. setAttribute ("totalPrice", 1000 );
%>
$ {SessionScope. totalPrice}
Note: The applicationScope variable should be used for accessing the application scope attributes instead of the pageContext variable.

Use functions in EL:

Static creation method:

To use the EL function on the JSP page, you need to create the following three files:
(1) method class file (*. java), which defines the Java method to be used in JSP.
(2) The tag library description file (*. tld), which maps each Java method to the function name.
(3) the JSP file (*. jsp) uses the tag library URI and function name to call the Java method.

To develop an EL function, you must first create the Java method to be called in JSP. In the following example, a method named add (String x, String y) is created to calculate the sum of the two passed String parameters.
Program 9.11 Compute. java
Remember the following points when creating an EL function:
(1) the class must be declared as public and the method must be declared as public static. In this way, the container can use the callback class method without creating a new object.
(2) class files should be saved in the/WEB-INF/classes directory.
(3) parameters and return values of methods in EL must be valid. Otherwise, the Web Container cannot identify the signature of the method.

To call these methods on the JSP page, you must create a tag library description file. The Tag Library description file (TLD) is mainly used to define the ing between static methods and function names.
The following TLD file implements the add ing between the add () method and the function named add.
Program 9.12 sampleLib. tld


9.4.1 create a static method
9.4.3 access EL functions in JSP

After creating a TLD file, it is very easy to call Java functions in JSP. This includes two steps:
(1) Use the taglib command to specify the prefix used by the function and the URI of the function. The URI must match the value of the <uri> element defined in the TLD file.
(2) create an EL expression using the prefix name and function name.
Program 9.13 sum. jsp


Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.