Java EL expressions

Source: Internet
Author: User
Tags arithmetic arithmetic operators function prototype numeric logical operators session id sessions
an El expression

I. El INTRODUCTION 1. Syntax Structure    ${expression} 2. [] with the. Operator    el provides. And [] Two operators to access the data.     when you want to access a property name that contains special characters, such as. or? etc. is not a symbol of letters or numbers, you must use []. For example:         ${user. My-name} should be changed to ${user["My-name"}     if you want to dynamically take a value, you can do it with [], and. cannot be dynamically fetched. For example:         ${sessionscope.user[data]} data is a variable 3. Variable     The method of El Access variable data is simple, for example: ${username}. It means to remove a variable whose name is username in a range.     because we don't specify which range of username, it will look for page, Request, session, application range.     if the way to find username, direct return, no longer continue to find, but if all the scope is not found, it will return null.     name in El for property         page          Pagescope         request          Requestscope         session          Sessionscope         application     Applicationscope          Ii. El implied object 1. Implied objects related to the scope the El implied object related to the scope contains the following four: Pagescope, Requestscope, Sessionscope, and Applicationscope; They are basically the same as JSP PageContext, request, session, and application; In El, these four suppressed objects can only be used to obtain the Range property value, that is, getattribute (String name), But cannot obtain other relevant information.

For example, to obtain a value that stores a property username in the session, you can use the following methods: Session.getattribute ("username") to obtain the username value, and in El, the following methods are used ${ Sessionscope.username}

2. The implied object associated with the input has two hidden objects related to the input: param and paramvalues, which are the more specific suppressed objects in El.

For example, when you want to take a user's request parameter, you can use the following methods: Request.getparameter (string name) request.getparametervalues (string name) in El you can use Param and    Paramvalues both to get the data. ${param.name} ${paramvalues.name}

3. Other implied objects

Cookie Jstl does not provide a cookie-setting action, for example: To obtain a value in the cookie that has a set name of Usercountry, you can use ${cookie.usercountry} to obtain it.

Header and Headervalues headers store data examples used by users ' browsers and services to communicate: To get the version of the user's browser, you can use ${header["User-agent"}. In addition, in rare opportunities, it is possible to have different values for the same header name, and you must instead use Headervalues to get the values.

Initparam Initparam gets set the environment parameter (context) example for the Web site: General method String UserID = (string) application.getinitparameter ("userid") ;     can use ${initparam.userid} to get the name UserID

PageContext PageContext Obtain additional information about the user's requirements or pages.    ${pageContext.request.queryString}         get the requested parameter string    ${pageContext.request.requestURL}         get the URL of the request, But does not include the requested parameter string    ${pageContext.request.contextPath}          Service's Web application name    ${pageContext.request.method}            methods of getting HTTP (get, POST)    ${pageContext.request.protocol}          Obtain the use of the Protocol (http/1.1, http/1.0)    ${pagecontext.request.remoteuser}          get user name    ${pagecontext.request.remoteaddr}          Obtain the user's IP address    ${pageContext.session.new}              Judgment Session is the new    ${pageContext.session.id}                get the session ID    ${pageContext.servletContext.serverInfo}   Obtaining service information on the host side

Three, El Operator 1. There are five arithmetic operators: + 、-、 * or $,/or div,%, or mod 2. There are six relational operators: = = or EQ,!= or NE, < or LT, > or GT, <= or LE, >=, or GE 3. Logical operators have three:& & OR, | | Or OR,!, or not 4. Other operators have three: empty operator, conditional operator, () operator example: ${empty param.name}, ${a? B:C}, ${a* (B+c)}

Four, El function (functions). Syntax: Ns:function (arg1, arg2, Arg3 ... argn) where NS is the predecessor name (prefix), it must be placed with the predecessor name of the TAGLIB directive

---------------------------------------------

Add:

<% @taglib prefix= "C" uri= "Http://java.sun.com/jstl/core_rt"%>

Foreach:

<c:foreachitems= "${messages}" var= "item" begin= "0" end= "9" step= "1" varstatus= "var" > ... </c:forEach>

Out:

The <c:outvalue= "/${logininfo.username}"/> c:out> outputs the contents of value to the current position, where the Logininfo attribute value of the Username object is output to the current position of the page. ${...} is the syntax of expression Language (EL) in JSP2.0. It defines an expression in which an expression can be a constant (as above) or a specific expression (as in the case of a Foreach loop body). Typical cases are as follows: Ø${logininfo.username} This indicates that the Username property referencing the Logininfo object is referenced. We can go through "." The operator refers to the properties of the object, or it can use "[]" to refer to the object property, such as ${logininfo[username]} and ${logininfo.username} to achieve the same effect. The meaning of the [] reference method is that if special characters appear in the property name, such as "." Or "-", you must use [] to get the value of the property to avoid grammatical conflicts (this phenomenon should be avoided as much as possible during system development). The equivalent JSP script is roughly as follows: Logininfo logininfo = (logininfo) session.getattribute ("Logininfo"); String username = logininfo.getusername (); As you can see, El greatly saves the amount of coding. Another problem that arises here is where EL will find the Logininfo object, and for an expression like ${logininfo.username}, the first is to find out whether the variable logininfo is previously defined from the current page. If not found, then go to request, session, application range until found. Returns null if a matching variable is not found until finally. If we need to specify the search scope for a variable, you can specify the search scope in El Expressions: ${pagescope.logininfo.username} ${requestscope.logininfo.username} ${ SessionScope.logininfo.username} ${applicationscope.logininfo.username} in spring, the result data returned by all the logical processing units will be placed as attributes ResetReturn to the HttpServletRequest object (see the Org.springframework.web.servlet.view.InternalResourceView in spring source code for a specific implementation.) The implementation code for the Exposemodelasrequestattributes method), which means that the resulting data object defaults to Requestscope in spring MVC. Therefore, in spring MVC, the following addressing methods should be used with caution: ${sessionscope.logininfo.username} ${applicationscope.logininfo.username}ø${1+2} The result is an expression that evaluates to an integer value of 3. Ø${I&GT;1} returns the bool type TRUE if the variable value is i>1. Compared with the above example, you can see that El automatically returns different data types based on the expression's evaluation results. Expressions are written in roughly the same way as expressions in Java code.

If/choose:

<c:iftest= "${var.index% 2 = 0}" > * </c:if> judgment condition is generally an El expression. <c:if> does not provide else clauses, may be inconvenient when used, we can use <c:choose> tag to achieve similar purposes: <c:choose> <c:when test= "${ Var.index% 2 = 0} "> * </c:when> <c:otherwise>! </c:otherwise> </c:choose> Similar to the switch statement in Java,<c:choose> provides a simplified approach to complex judgment conditions. Where the <c:when> clause is similar to a case clause, it can occur multiple times. The above code outputs the "*" number at odd rows, and the even row outputs "!". ---------------------------------------------

Further added:

The 1 El expression is represented by ${} and can be used in all HTML and JSP tags to replace the complex Java code in the JSP page.

2 El expressions manipulate constant variables and implicit objects. The most commonly used implicit objects are ${param} and ${paramvalues}. ${param} represents a value that returns a single string in the request parameter. ${paramvalues} represents a set of values that return a request parameter. pagescope represents a variable of a page range. Requestscope represents a variable of the request object. Sessionscope represents a variable within the scope of a session. Applicationscope represents a variable of the scope of the application.

3 <%@ page iselignored= "True"%> indicates whether the El language is disabled, true to prohibit. False indicates that the default enabled El language is not prohibited in. JSP2.0.

4 El language can display logical expressions such as ${true and false} result is false relational expression such as ${5>6} result is false arithmetic expression such as ${5+5} result is 10

The variable search scope in 5 El is: page request session application dot operator (.) and "[]" are the values that represent the get variable. The difference is [] a description of the El Expression in a variable jsp that can display a non-part of speech

definition of Jspel language

E L (Expression Language) Purpose: To make JSP easier to write.

Expression languages are inspired by the ECMAScript and XPath expression languages, which provide a way to simplify expressions in a JSP.        It is a simple language, based on available namespaces (PageContext properties), nested properties and accessors for collections, operators (arithmetical, relational, and logical), extensible functions that map to static methods in Java classes, and a set of implicit objects. EL provides the ability to use run-time expressions outside the scope of the JSP scripting elements. Scripting elements are elements in a page that can be used to embed Java code in a JSP file. They are typically used for object manipulation and for performing calculations that affect what is generated. JSP 2.0 adds an EL expression as a scripting element.

Second, JSP el introduction

1. Syntax structure      ${expression} 2, [] with. Operator      EL provide "." and "[]" two operators to access the data.      when you want to access a property name that contains special characters, such as. or? etc. is not a symbol of letters or numbers, you must use []. For example:          ${user. My-name} should be changed to ${user["My-name"}      if you want to dynamically take a value, you can do it with [], and "." Dynamic values cannot be achieved. For example:          ${sessionscope.user[data]} data is a variable 3, variable       EL access to variable data is simple, for example: ${username}. It means to remove a variable whose name is username in a range.      because we don't specify which range of username, it will look for page, Request, session, application range.      if the way to find username, direct return, no longer continue to find, but if all the scope is not found, it will return null.      name in El for property          page           Pagescope          request           Requestscope &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;  session          Sessionscope           application      Applicationscopeii. valid expressions in JSP EL

A valid expression can contain text, an operator, a variable (an object reference), and a function call. We'll look at each of these valid expressions separately: 1, text

The JSP expression language defines the following text that can be used in an expression:

Text

The value of the literal

Boolean

True and False

Integer

Similar to Java. Can contain any positive or negative numbers, such as 24,-45, 567

Floating point

Similar to Java. Can contain any positive or negative floating-point numbers, such as -1.8E-45, 4.567

String

Any string that is qualified by either single or double quotes. For single quotes, double quotes, and backslashes, the backslash character is used as the escape sequence. It is important to note that if you use double quotes at both ends of a string, single quotes do not need to be escaped.

Null

Null

2. Operator

The JSP expression language provides the following operators, most of which are commonly used operators in Java:

Terms

Defined

Arithmetic type

+,-(two Yuan), *,/, Div,%, mod,-(one yuan)

Logical type

And, &&, or, | | 、!、 not

Relationship Type

= =, eq,!=, NE, GT, <=, le, >=, GE. You can compare to other values, or to a Boolean, String, Integer, or floating-point literal.

Empty

The null operator is a prefix operation that can be used to determine whether a value is empty.

Conditional type

A? B:c. Assign a value of B or C according to the result of a assignment.

3. Implicit Object

The JSP expression language defines an implicit set of objects, many of which are available in JSP Scriplet and expressions:

PageContext

The context of the JSP page. It can be used to access JSP implicit objects such as requests, responses, sessions, outputs, ServletContext, and so on. For example, ${pagecontext.response} assigns a value to a page's response object.

In addition, several implicit objects are provided that allow easy access to the following objects:

Terms

Defined

Param

Maps the request parameter name to a single string parameter value (obtained by calling Servletrequest.getparameter (string name)). The GetParameter (String) method returns a parameter with a specific name. The expression $ (param.name) is the equivalent of Request.getparameter (name).

Paramvalues

Maps the request parameter name to a numeric array (obtained by calling Servletrequest.getparameter (String name)). It is very similar to a Param implicit object, but it retrieves an array of strings instead of a single value. Expression ${paramvalues.name) is the equivalent of request.getparamtervalues (name).

Header

Maps the request header name to a single string header value (obtained by calling Servletrequest.getheader (String name)). The expression ${header.name} is the equivalent of Request.getheader (name).

Headervalues

Maps the request header name to a numeric array (obtained by calling Servletrequest.getheaders (String)). It is very similar to the header implicit object. The expression ${headervalues.name} is the equivalent of request.getheadervalues (name).

Cookies

Maps a cookie name to a single Cookie object. A client request made to the server can obtain one or more cookies. An expression ${cookie.name.value} returns the first cookie value with a specific name. If the request contains multiple cookies with the same name, you should use the ${headervalues.name} expression.

Initparam

Maps a context initialization parameter name to a single value (obtained by calling Servletcontext.getinitparameter (String name)).

In addition to the two types of implicit objects mentioned above, there are also objects that allow access to a wide range of variables, such as Web contexts, sessions, requests, pages:

Terms

Defined

Pagescope

Maps the variable name of a page range to its value. For example, an EL expression can access a page-wide object in a JSP using ${pagescope.objectname}, and you can access the object's properties using ${pagescope.objectname.attributename}.

Requestscope

Maps the variable name of the request scope to its value. This object allows access to the properties of the requested object. For example, an EL expression can access an object of a JSP request range using ${requestscope.objectname} and access the properties of the object using ${requestscope.objectname.attributename}.

Sessionscope

Maps a session-scoped variable name to its value. This object allows access to the properties of the session object. For example:

$sessionScope. Name}

Applicationscope

Maps an application-scoped variable name to its value. This implicit object allows access to application-scoped objects.

third, special emphasis is placed on:

1. Note that when an expression refers to one of these objects by name, the corresponding object is returned instead of the corresponding property. For example, ${pagecontext} returns the PageContext object even if the existing PageContext property contains some other values.

2. Note that <%@ pageiselignored= "true"%> indicates whether the El language is disabled, and True indicates that the. False indicates that the default enabled El language in. JSP2.0 is not prohibited. Iv. Illustrative Examples

1, for example,

<%=request.getparameter ("username")% > equivalent to ${param.username}

2, for example, but the following El language can be completed if a username is empty, the null is not displayed, but the value is not displayed.

<%=USER.GETADDR ()%> is equivalent to ${user.addr}.

3, for example:

<% =request.getattribute ("userlist")%> equivalent to $ {requestscope.userlist}

4, for example, the principle is as above example 3.

${Sessionscope.userlist} 1

${Sessionscope.userlist} 2

${Applicationscope.userlist} 3

${Pagescope.userlist} 4

${uselist} Meaning: Execution order is 4 1 2 3.

“.” The back is just a string, not a real built-in object, and cannot invoke the object.

4, for example,

<%=USER.GETADDR ()%> equivalent to ${user.addr}

The user in front of the first sentence is a variable.

After the second sentence, user must be an attribute in a certain range.

El is a way to use in JSP pages
The syntax of El syntax El is very simple, his greatest feature is the use of a convenient example: ${sessionscope.user.sex} All El are starting with ${, with the end of}. The above El paradigm means that the user's gender is obtained from the session.
  If you use the previous JSP code as follows: <% User user = (user) Session.getattribute ("User");
 String sex = User.getsex ();

%> The syntax of El is more convenient and concise than the traditional JSP code compared to the two. El offers. and [] Two operators to access the data, [] You can access the collection or the elements of the array, the Bean's properties.

The following two represent the same meaning, but it is necessary to ensure that the properties of the object to be obtained have the corresponding setxxx () and GetXXX () methods. Example: ${sessionscope.user.sex} equals ${sessionscope.user["Sex"]}.

And [] can also be mixed at the same time, as follows: ${sessionscope.shoppingcart[0].price} returns the price of the first item in ShoppingCart.

In El, a string can use ' ABC ' and can use ' abc '.

The arithmetic operators of El operator El are roughly the same as the operators in Java and have the same precedence.

Note: the ' + ' operator does not concatenate strings, he is only used for addition operations.    The El relational operator has the following six operator relational operators to illustrate the example result = = or EQ | equals |${5 = = 5} or ${5 eq 5} |   True!= or NE | Not equal to |${5!= 5} or ${5 ne 5} |   False < LT | Less than |${3 < 5} or ${3 lt 5} |   True > or GT | Greater than |${3 > 5} or ${3 GT 5} |  False <= or Le | Less than or equal to |${3 <= 5} or ${3 le 5} |  True >= or GE | Bigis equal to |${3 >= 5} or ${3 ge 5} | False empty operator Empty operator is primarily used to determine whether a value is null or empty, for example: ${empty Param.name} Next describes the rules for the empty operator: {empty} A If a is null, return TRUE if When a does not exist, returns true if A is an empty string, returns True if A is an empty array, returns True if A is an empty map, returns True if A is an empty collection, returns True otherwise, returns false note: in the The El relational operator cannot be written as: ${param.password1} = = ${param.password2} or ${${param.password1} = = ${Param.password2}} and should be written as ${PA Ram.password1 = = Param.password2} Use El to get data from a form there are two hidden objects related to the input: param and paramvalues, which are the more specific suppressed objects in El.

Generally speaking, when we take a user's request parameter, we can use the following methods: Request.getparameter (string name) request.getparametervalues (string name)
In El, you can use both Param and paramvalues to get the data.

${param.name} ${paramvalues.name} can get the value of all parameters with the same name ${paramvalues.hobbies[0]} You can access the value of a particular parameter by specifying a subscript
Here the Param function is the same as Request.getparameter (string name), and Paramvalues and Request.getparametervalues (string name) are the same.

If the user fills out a text box with a form,form name of username, we can use ${param.username} to get the value of the user's fill in the text box.

Use functions in El function El to write a class to use the method, and then configure the Xxx.tld file and then use it in the JSP to resemble the custom label for the JSP. Configuration <functio in Xxx.tldN> <name>reverse</name><!--function name--> <function-class>jsp2.examples.el.functions</ function-class><!--function in the class--> <function-signature>java.lang.string reverse (java.lang.String) </ Function-signature> <!--function prototype, which is the return value type of function, function name, parameter table, note that you must write the full name of the type--> </function> use the notation of the El function ${sn:upper ('    ABC ')} Note: When you define an El function, you must also use the properties set in the built-in objects for the implied object El that exposes static (public) El, and you need to use a specific El Built-in object property range |     Object Page in El |     Pagescope Request |     Requestscope Session |     Sessionscope Application | The properties of the built-in objects in Applicationscope El ${requestscope.user} are equivalent to <%request.getattribute ("user")%> if you do not write a specific range, That would be a search between different scopes. Example: {User} (user is in the request range Request.setattribute ("user", user) is equal to ${requestscope.user} <% Request.getattribute ("user")%>
El expression Language
The El language is the Jstl output (input) representation of a Java expression.
In Jstl, the El language can only be used in attribute values. The El language can only be invoked by establishing an expression ${EXP1}. There are three ways to use an expression in an attribute value.

1, the Value property contains an expression
<some:tag value= "${expr}"/>
In this case, the expression value is computed and assigned to the Value property based on the type conversion rule. For example: <c:out value= "${username}"/> ${username} is an EL, which is equivalent to the JSP statement <%=request.getattribute ("username")%> or <%=session.getattribute ("username")%>

2. The Value property contains one or more properties that are split by text or surround
<some:tag value= "some${expr}${expr}text${expr}"/>
In this case, the expression is evaluated from left to right and the result is converted to a string type (based on the type conversion rule) and the result is assigned to the Value property

3, the Value property contains only text
<some:tag value= "Sometext"/>
In this case, the string property value is converted to the type that the label expects based on the type conversion rule.

Operator for El language
Gets the value of an attribute in an object or collection
To get the properties in the collection, El supports the following two actions
1. Use the. operator to obtain a named attribute. For example, an expression ${user.username} indicates the Username property of the object user
2. Use the [] operator to obtain a name or numeric attribute.
Expression ${user["username"]} has the same meaning as expression ${user. Username}
Expression ${row[0]} indicates the first entry of the row collection.
Here the user is an object of a class whose attribute username must conform to the standard JavaBean specification, that is, the appropriate getter and setter method must be defined for the Username property.

Empty operator (null value check)

Use the empty operator to determine whether an object, collection, or string variable is null or NULL. For example:
${empty Param.username}
If the username value in the parameter list for the request is null, the value of the expression is true. El can also be compared directly with NULL using the comparison operator. such as ${param.firstname = = null}.
Comparison operator operator Description = = or EQ equality check!= or NE inequality check < or LT is less than check > or GT greater than check <= or le less than equal check >= or GE is greater than or equal to check
Numeric operators and logical operators are the same as the Java language and are no longer listed.

The 1 El expression is represented by ${} and can be used in all HTML and JSP tags to replace the complex Java code in the JSP page.

2 El expressions manipulate constant variables and implicit objects. The most commonly used implicit objects are ${param} and ${paramvalues}. ${param} represents a value that returns a single string in the request parameter. ${paramvalues} Represents a set of values that return a request parameter. pagescope represents a variable of a page range. Requestscope represents a variable of the Request object. Sessionscope represents a variable within the scope of a session. Applicationscope represents a variable of the scope of the application.

3 <%@ page iselignored= "True"%> indicates whether the El language is disabled, true to prohibit. False indicates that the default enabled El language is not prohibited in. JSP2.0.

4 El language can display logical expressions such as ${true and false} result is false relational expression such as ${5>6} result is false arithmetic expression such as ${5+5} result is 10

The variable search scope in 5 El is: page request session application dot operator (.) and "[]" are the values that represent the get variable. The difference is [] You can show variables that are not part of speech

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.