Jsp EL expression and jspel expression

Source: Internet
Author: User

Jsp EL expression and jspel expression

EL expression

EL Full name: Expression Language

EL syntax is very simple. Its biggest feature is its ease of use. Next we will introduce the main syntax structure of EL:

$ {SessionScope. user. sex}

All EL types start with $ {and end. The preceding EL example indicates that the data is obtained from the Session range.

User gender. If the preceding JSP Scriptlet statement is used as follows:

User user = (User) session. getAttribute ("user ");

String sex = user. getSex ();

In comparison, the EL syntax is more convenient and concise than the traditional JSP Scriptlet syntax.

. And [] Operators

EL provides the. and [] operators to navigate data. The two represent the same:

$ {SessionScope. user. sex} equals $ {sessionScope. user ["sex"]}

. And [] can also be used together, as follows:

$ {SessionScope. shoppingCart [0]. price}

The returned result is the price of the first item in shoppingCart.

However, there are two differences between the two:

(1) When the attribute name to be accessed contains some special characters, such. or-is not a letter or number, you must use [], for example: $ {user. my-Name}

The preceding method is incorrect and should be changed to: $ {user ["My-Name"]}.

(2) Let's consider the following situations:

$ {SessionScope. user [data]}

In this case, data is a variable. If the value of data is "sex", the above example is equivalent to $ {sessionScope. user. sex };

If the value of data is "name", it is equivalent to $ {sessionScope. user. name }. Therefore, if you want to dynamically set the value, you can use the above method, but you cannot set the dynamic value.

EL variable

EL is easy to access variable data, for example, $ {username }. It means to retrieve the variable named username in a range. Because we didn't specify the username in which range, the default value of the username will be found from the Page range first. If it cannot be found, it will be sorted to the Request, Session, and Application range in sequence. If the username is found on the way, it will be returned directly and will not be found any more, but if all the ranges are not found, null will be returned. Of course, the EL expression will be optimized, the page is blank, instead of printing the output NULL.

Attribute range (jstl name)

Name in EL

Page

Pagination

Request

RequestScope

Session

SessionScope

Application

ApplicationScope

We can also specify the variable in which range to retrieve:

Example

Description

$ {Pagination. username}

Retrieve the username variable in the Page range.

$ {RequestScope. username}

Retrieve the username variable in the Request range

$ {SessionScope. username}

Retrieve the username variable in the Session range

$ {ApplicationScope. username}

Retrieve the username variable in the Application range.

Among them, pagination, requestScope, sessionScope, and applicationScope are all hidden objects of EL. Their names can easily guess what they mean, for example: $ {sessionScope. username} is the username variable used to retrieve the Session range. This method is better than the previous JSP method:

String username = (String) session. getAttribute ("username"); easy and concise.

Automatic Conversion Type

In addition to the syntax that provides convenient access to variables, EL also provides a convenient function: automatically changing the type. Let's look at the following example:

$ {Param. count + 20}

If the value of count in the form is 10, the above result is 30. Readers who have never touched JSP before may take the above example for granted, but they cannot do so in JSP 1.2 because of the value transmitted from the form, they all belong to the String type. Therefore, after receiving them, you must convert them to other types, such as int and float, before performing some mathematical operations, the following is the previous practice:

String str_count = request. getParameter ("count ");

Int count = Integer. parseInt (str_count );

Count = count + 20;
Therefore, be careful not to confuse java syntax (the number is converted to a string when the string and number are connected with "+.


EL implicit object

JSP has nine implicit objects, and EL also has its own hidden objects. There are a total of 11 EL implicit objects

Implicit object

Type

Description

PageContext

Javax. servlet. ServletContext

PageContext of the JSP

Pagination

Java. util. Map

Obtains the value corresponding to the attribute name in the Page range.

RequestScope

Java. util. Map

Obtains the value corresponding to the attribute name in the Request range.

SessionScope

Java. util. Map

Obtains the value corresponding to the attribute name in the Session range.

ApplicationScope

Java. util. Map

Obtains the value corresponding to the attribute name in the Application range.

Param

Java. util. Map

Like ServletRequest. getParameter (String name ). Returns a value of the String type.

ParamValues

Java. util. Map

Like ServletRequest. getParameterValues (String name ). Returns a value of the String [] type.

Header

Java. util. Map

Like ServletRequest. getHeader (String name ). Returns a value of the String type.

HeaderValues

Java. util. Map

Like ServletRequest. getHeaders (String name ). Returns a value of the String [] type.

Cookie

Java. util. Map

Like HttpServletRequest. getCookies ()

InitParam

Java. util. Map

Like ServletContext. getInitParameter (String name ). Returns a value of the String type.

 

However, it should be noted that if you use EL to output a constant, double quotation marks should be added to the string. Otherwise, EL will treat the constant you think as a variable by default, at this time, if the variable does not exist in the four declared ranges, it will output null, and if so, the value of the variable will be output.

Attribute and Scope)

The EL implied objects related to the scope include the following four: pagination, requestScope, sessionScope, and

ApplicationScope, which is basically the same as pageContext, request, session, and application of JSP. Therefore, I will give a brief description here. However, it must be noted that the four implicit objects can only be used to obtain the range property value, that is, getAttribute (String name) in JSP, but cannot obtain other related information. For example: in addition to access attributes, the request object in JSP can also obtain the user's request parameters or header information. However, in EL, it can only be used to obtain the attribute value of the corresponding range. For example, we need to store an attribute in the session. Its name is username and session is used in JSP. getAttribute ("username") to get the value of username, but in EL, $ {sessionScope is used. username} to get its value.

Cookie

The so-called cookie is a small text file. It records the Session Tracking content in the text file in key and value mode. This text file is usually stored in the temporary storage area of the browser. JSTL does not provide the cookie setting action, because this action is usually required by backend developers, rather than being handed over to front-end developers. If we set a value named userCountry in the cookie, we can use $ {cookie. userCountry} to retrieve it.

Header and headerValues

The header stores the data used by the browser and server for communication. When the user requests the webpage of the server, a header file that records the required information is sent, for example: the user's browser version, the region set by the user's computer, and other related data. If you want to obtain the version of your browser, that is, $ {header ["User-Agent"]}. In addition, it is rare that the same header name may have different values. In this case, you must use headerValues to obtain these values.

Note: Because the User-Agent contains the special character "-", you must use "[]" instead "-".

$ (Header. User-Agent ).


InitParam

Just like other attributes, we can set the environment parameters (Context) of the web Platform on our own. When we want to get these parameters initParam, just like other attributes, you can set the environment parameters (Context) of the web platform.

<? Xml version = "1.0" encoding = "ISO-8859-1"?>

<Web-app xmlns = "http://java.sun.com/xml/ns/j2ee"

Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"

Xsi: schemaLocation = "http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"

Version = "2.4">:

<Context-param>

<Param-name> userid </param-name>

<Param-value> mike </param-value>

</Context-param>:

</Web-app>

Then we can directly use $ {initParam. userid} to obtain the parameter named userid with the value of mike. The following is the previous practice: String userid = (String) application. getInitParameter ("userid ");

Param and paramValues
The following method is usually used to obtain user parameters:

Request. getParameter (String name)
Request. getParameterValues (String name)

In EL, you can use param and paramValues to obtain data.
$ {Param. name}
$ {ParamValues. name}

Here, param functions are the same as request. getParameter (String name), while paramValues and
Request. getParameterValues (String name) is the same. If you enter a table named username, you can use $ {param. username} to obtain the value you entered.

 

Here, we should make it clear that EL expressions can only use built-in object values, that is, read-only operations. If you want to perform write operations, let the background code complete, after all, the EL expression is only the output tag on The View.

PageContext

We can use $ {pageContext} to obtain other details about user requirements or pages. The following table lists several common parts.

Expression

Description

$ {PageContext. request. queryString}

GET request parameter string

$ {PageContext. request. requestURL}

Get the request URL, but does not include the request parameter string, that is, the HTTP address of the servlet.

$ {PageContext. request. contextPath}

The name of the webapplication of the service.

$ {PageContext. request. method}

Get http (GET, POST)

$ {PageContext. request. protocol}

Obtain the used 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}

Judge whether the session is new. The so-called new session indicates that the session is generated by the server and the client is not used.

$ {PageContext. session. id}

Obtains the session ID.

$ {PageContext. servletContext. serverInfo}

Obtain host service information

This object can effectively improve the hard coding of the Code. For example, the tag link on the page accesses a servlet, if the HTTP address of the SERVLET is written to death, the source code must be modified when the SERVLET's SERVLET-MAPPING changes, so the maintainability will be greatly reduced.

EL arithmetic operations

Many arithmetic and logical operators are supported by expression language. All Arithmetic Operators supported by Java can be used by expression language; even some arithmetic and logical operators not supported by Java are supported by the expression language.

 

Code
<% @ Page contentType = "text/html; charset = gb2312 "%>

The above page demonstrates the addition, subtraction, multiplication, division, and remainder Arithmetic Operators supported by Expression Language. Readers may also find that expression language supports div, mod, and other operators. In addition, the expression language treats all values as floating point numbers, so the essence of 3/0 is 3.0/0.0. The result is Infinity.

If you need to normally output the "$" symbol on the page that supports Expression Language, add the Escape Character "\" before the "$" symbol. otherwise, the system considers "$" as a special identifier of the expression language.

EL Relational operators

Relational operators

Description

Example

Result

= Or eq

Equal

${5 = 5} or $ {5eq5}

True

! = Or ne

Not equal

$ {5! = 5} or $ {5ne5}

False

<Or lt

Less

${3 <5} or $ {3lt5}

True

> Or gt

Greater

$ {3> 5} or {3gt5}

False

<= Or le

Less than or equal

${3 <= 5} or $ {3le5}

True

> = Or ge

Greater than or equal

5} or $ {3ge5}

False

The expression language can be compared between numbers, characters, and characters. The comparison of strings is based on the corresponding UNICODE value.

Note: when using the EL relational operator, it cannot be written:
$ {Param. password1 }== {param. password2}
Or
$ {$ {Param. password1 }== {param. password2 }}
And should be written
$ {Param. password1 = param. password2}


EL logical operators

Logical operators

Example

Result

& Or and

Intersection $ {A & B} or $ {A and B}

True/false

| Or

Union $ {A | B} or $ {A or B}

True/false

! Or not

Not $ {! A} or $ {not}

True/false

 

Empty Operator

The Empty operator is mainly used to determine whether the value is NULL (NULL, NULL String, Empty set ).

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.