Detailed explanation of the usage of El expression in JSP (required article)

Time:2019-10-27

El full name is expression language

El syntax is very simple, its biggest feature is very convenient to use. Next, the main syntax structure of El is introduced:

${sessionScope.user.sex}

All EL starts with ${and ends with}. The above El example means: from the scope of the session, get

Gender of the user. If you write JSP scriptlet as follows:

User user =(User)session.getAttribute(“user”);

String sex =user.getSex( );

By comparison, we can find that El syntax is more convenient and concise than traditional JSP scriptlet.

El expressions are used with JSTL. You need to introduce JSTL tag library (< C: foreach items = “” > < C: foreach >, < C: if test = “” > < C: if >, etc. belong to JSTL expression)

<% @ taglib URI = “namespace of JSP tag” prefix = “C”% >

. and [] operators

El provides. And [] operators to navigate data. The following two mean the same:

${sessionscope. User. Sex} equals ${sessionscope. User [“sex”]}

. and [] can also be mixed at the same time, as follows:

${sessionScope.shoppingCart[0].price}

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

However, there will be differences between:

(1) when the attribute name to be accessed contains some special characters, such as symbols that are not letters or numbers, it is necessary to use [],

For example: ${user. My name}

The above is not the correct way, it should be changed to: ${user [“my name”]}

(2) let’s consider the following situations:

${sessionScope.user[data]}

At this time, data is a variable. If the value of data is “sex”, the above example is equal to ${sessionscope. User. Sex};

If the value of data is “name”, it is equal to ${sessionscope. User. Name}.

Therefore, if we want to take dynamic value, we can use the above methods, but we can’t do dynamic value.

EL variable

El has a simple way to access variable data, such as ${username}. It means to take out a variable named username from a range.

Because we didn’t specify which range’s username, its default value will be found from the page range first. If it can’t be found,

Then go to the request, session and application ranges in order. If you find username on the way, you can send it back directly, instead of continuing to find it.

But if all the ranges are not found, null will be returned. Of course, El expression will be optimized to display blank on the page instead of printing out null.

Property range (JSTL name)

Name in El

Page

PageScope

Request

RequestScope

Session

SessionScope

Application

ApplicationScope

We can also specify which range of variables to take out:

Example

Explain

${pageScope.username}

Take out the username variable of the page range

${requestScope.username}

Get the username variable of the request range

${sessionScope.username}

Take out the username variable of the session scope

${applicationScope.username}

Take out the username variable of the application scope

Among them, pagescope, requestscope, sessionscope and applicationscope are all implied objects of El.

It’s easy to guess what they mean by their names.

For example: ${sessionscope. Username} is the username variable that takes out the session scope. Is this writing method better than the previous JSP writing method?

String username = (string) session. Getattribute (“username”); much easier and simpler.

Autotransformation type

In addition to providing a syntax for easy access to variables, El has another convenient function: automatic transformation of types. Let’s take the following example:

${param.count + 20}

If the value of count from the form is 10, the above result is 30. Readers who have not been exposed to JSP before may take the above example for granted.

But you can’t do this in JSP 1.2 because the values from the form are of the same type as string, so when you receive them, you have to convert them to other types.

For example, int, float, and so on. Then some mathematical operations can be performed. Here is the previous method:

String str_count =request.getParameter(“count”);

int count =Integer.parseInt(str_count);

count = count + 20;
So, be careful not to get confused with Java syntax (when strings and numbers are linked with “+”, numbers are converted to strings).

El implied object

JSP has nine implied objects, and El has its own. There are 11 El implied objects in total

Implicit Object

type

Explain

PageContext

javax.servlet.ServletContext

Pagecontext representing this JSP

PageScope

java.util.Map

Gets the value corresponding to the property name of the page range

RequestScope

java.util.Map

Get the value corresponding to the property name of the request scope

sessionScope

java.util.Map

Gets the value corresponding to the property name of the session scope

applicationScope

java.util.Map

Gets the value corresponding to the property name of the application scope

param

java.util.Map

Like ServletRequest. Getparameter (string name). Returns a value of type string

paramValues

java.util.Map

Like ServletRequest. Getparametervalues (string name). Returns a value of type string [].

header

java.util.Map

Like ServletRequest. Getheader (string name). Returns a value of type string

headerValues

java.util.Map

Like ServletRequest. Getheaders (string name). Returns a value of type string [].

cookie

java.util.Map

Like HttpServletRequest. Getcookies()

initParam

java.util.Map

Like ServletContext. Getinitparameter (string name). Returns a value of type string

However, it should be noted that if you want to output a constant with El, the string should be enclosed in double quotation marks, 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 declaration ranges, it will output null. If it exists, it will output the value of the variable.

Attribute and scope

The El implied objects related to scope include the following four: pagescope, requestscope, sessionscope, and

Applicationscope, they are basically the same as the pagecontext, request, session and application of JSP, so I will just explain them here.

However, it must be noted that these four implicit objects can only be used to get the range attribute value, that is, getattribute (string name) in JSP, but not other relevant information.

For example, the request object in JSP can not only access the attributes, but also obtain the user’s request parameters or header information and so on.

But in El, it can only be used to get the property value of the corresponding range.

For example, we want to store an attribute in the session, whose name is username, and use session. Getattribute (“username”) in JSP to get the value of username.

In El, however, it uses ${sessionscope. Username} to get its value.

cookie

The so-called cookie is a small text file. It records the content of session tracking in the text file in the way of key and value. The text file usually exists in the temporary storage area of the browser.

JSTL does not provide the action of setting cookies, because this action is usually something the back-end developers have to do, rather than give it to the front-end developers.

If we set a value named usercountry in the cookie, we can use ${cookie. Usercountry} to get it.

Header and headervalues

The header stores the data used by the user browser and the server for communication. When the user requests the server’s web page, a header file will be sent to record the required information, such as the version of the user browser, the area set by the user’s computer and other relevant data. If you want to get the version of the user browser, that is ${header [“user agent”]}. In addition, under rare opportunities, it is possible that the same header name has different values. At this time, the headervalues must be used instead to obtain these values.

Note: because the user agent contains the special character ‘-‘, it must use ‘[]’ instead of being written as

$(header.User-Agent)。

initParam

Like other attributes, we can set the environment parameters (context) of the web site by ourselves. When we want to obtain these parameters, initparam is like other attributes.

We can set the environment parameters (context) of the web site by ourselves, when we want to obtain these parameters


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

<web-appxmlns="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 get the parameter named userid with the value of Mike.

The following is the previous method: String userid = (string) application.getinitparameter (“userid”);

Param and paramvalues

The following methods are usually used to get user parameters:

request.getParameter(String name)
request.getParameterValues(String name)

In El, you can use both param and paramvalues to get data.
${param.name}
${paramValues.name}

Here, the function of param is the same as that of request.getparameter (string name), while paramvalues and
The request.getparametervalues (string name) are the same. If the user fills in a table named username, then we can use ${param. Username} to get the value the user fills in.

As you can see here, it should be clear that El expressions can only take values through built-in objects, that is, read-only operations. If you want to write, let the background code do it. After all, El expressions are only output labels on views.

pageContext

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

Expression

Explain

${pageContext.request.queryString}

Get the requested parameter string

${pageContext.request.requestURL}

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

${pageContext.request.contextPath}

The name of the webapplication for the service

${pageContext.request.method}

Get HTTP method (get, post)

${pageContext.request.protocol}

Get the protocol used (HTTP / 1.1, http / 1.0)

${pageContext.request.remoteUser}

Get user name

${pageContext.request.remoteAddr}

Get the IP address of the user

${pageContext.session.new}

Judge whether the session is new. The so-called new session indicates that the client has not been used since it was just generated by the server.

${pageContext.session.id}

Get the ID of the session

${pageContext.servletContext.serverInfo}

Get the service information of the host

This object can effectively improve the hard coding problem of the code. For example, there is an a tag link in the page to access a servlet, if the HTTP address of the servlet is written dead

If the servlet-mapping of the servlet is changed, the source code must be modified, so the maintainability will be greatly reduced.

El arithmetic operation

The expression language supports a lot of arithmetic operators and logical operators. All the arithmetic operators and expression languages supported in the Java language can be used.

Even the Java language does not support some arithmetic and logical operators, expression language also supports.

<%@ page contentType="text/html; charset=gb2312"%>
<html>
<head>
< title > expression language - arithmetic operator < / Title >
</head>
<body>
<h2>Expression language arithmetic operators</h2>
<hr>
<table border="1" bgcolor="aaaadd">
<tr>
<td><b>Expression language</b></td>
<td><b>Calculation results</b></td>
</tr>
<! -- direct output constant -- >
<tr>
<td>${1}</td>
<td></td>
</tr>
<! -- calculate addition -- >
<tr>
<td>${1.2 + 2.3}</td>
<td>${1.2 + 2.3}</td>
</tr>
<! -- calculate addition -- >
<tr>
<td>${1.2E4 + 1.4}</td>
<td>${1.2E4 + 1.4}</td>
</tr>
<! -- Calculation subtraction -- >
<tr>
<td>${-4 - 2}</td>
<td>${-4 - 2}</td>
</tr>
<! -- calculate multiplication -- >
<tr>
<td>${21 * 2}</td>
<td>${21 * 2}</td>
</tr>
<! -- Calculation Division -- >
<tr>
<td>${3/4}</td>
<td>${3/4}</td>
</tr>
<! -- Calculation Division -- >
<tr>
<td>${3 div 4}</td>
<td>${3 div 4}</td>
</tr>
<! -- Calculation Division -- >
<tr>
<td>${3/0}</td>
<td>${3/0}</td>
</tr>
<! -- calculate remainder -- >
<tr>
<td>${10%4}</td>
<td>${10%4}</td>
</tr>
<! -- calculate remainder -- >
<tr>
<td>${10 mod 4}</td>
<td>${10 mod 4}</td>
</tr>
<! -- evaluate the binocular operator -- >
<tr>
<td>${(1==2) ? 3 : 4}</td>
<td>${(1==2) ? 3 : 4}</td>
</tr>
</table>
</body>
</html>
<%@ page contentType="text/html; charset=gb2312"%>
<html>
<head>
< title > expression language - arithmetic operator < / Title >
</head>
<body>
<h2>Expression language arithmetic operators</h2>
<hr>
<table border="1" bgcolor="aaaadd">
<tr>
<td><b>Expression language</b></td>
<td><b>Calculation results</b></td>
</tr>
<! -- direct output constant -- >
<tr>
<td>${1}</td>
<td></td>
</tr>
<! -- calculate addition -- >
<tr>
<td>${1.2 + 2.3}</td>
<td>${1.2 + 2.3}</td>
</tr>
<! -- calculate addition -- >
<tr>
<td>${1.2E4 + 1.4}</td>
<td>${1.2E4 + 1.4}</td>
</tr>
<! -- Calculation subtraction -- >
<tr>
<td>${-4 - 2}</td>
<td>${-4 - 2}</td>
</tr>
<! -- calculate multiplication -- >
<tr>
<td>${21 * 2}</td>
<td>${21 * 2}</td>
</tr>
<! -- Calculation Division -- >
<tr>
<td>${3/4}</td>
<td>${3/4}</td>
</tr>
<! -- Calculation Division -- >
<tr>
<td>${3 div 4}</td>
<td>${3 div 4}</td>
</tr>
<! -- Calculation Division -- >
<tr>
<td>${3/0}</td>
<td>${3/0}</td>
</tr>
<! -- calculate remainder -- >
<tr>
<td>${10%4}</td>
<td>${10%4}</td>
</tr>
<! -- calculate remainder -- >
<tr>
<td>${10 mod 4}</td>
<td>${10 mod 4}</td>
</tr>
<! -- evaluate the binocular operator -- >
<tr>
<td>${(1==2) ? 3 : 4}</td>
<td>${(1==2) ? 3 : 4}</td>
</tr>
</table>
</body>
</html>

The above page demonstrates the functions of arithmetic operators such as addition, subtraction, multiplication, division and remainder supported by the expression language. Readers may also find that the expression language also supports operators such as div and mod.

Moreover, the expression language treats all values as floating-point numbers, so the essence of 3 / 0 is 3.0/0.0, and the result should be infinity.

If you need to output the “$” symbol in the page that supports expression language normally, add the escape character “\” before the “$” symbol, otherwise the system thinks “$” is a special mark of expression language.

El relational operator

Relational operators

Explain

Example

Result

= = or EQ

Be equal to

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

true

! = or ne

Not equal to

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

false

< or LT

less than

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

true

> or GT

greater than

${3 > 5} or {3gt5}

false

< or le

Less than or equal to

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

true

> = or Ge

Greater than or equal to

5} or ${3ge5}

false

Expression language can be compared not only between numbers, but also between characters. String comparison is based on its corresponding Unicode value.

Note: when using the El relational operator, it cannot be written as:

${param.password1} = =${param.password2}

perhaps
${ ${param.password1 } = = ${param.password2 } }

And should be written

${ param.password1 = =param.password2 }

El logical operator

Logical operators

Example

Result

& or and

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

true/false

Or or

Union ${a | B} or ${a or B}

true/false

Or not

Non ${! A} or ${not a}

true/false

Empty operator

Empty operator is mainly used to determine whether the value is empty (null, empty string, empty collection).

Conditional operator

${ A ? B : C}

The detailed explanation of the usage of El expression in the above JSP (see article) is the whole content shared by the editor. I hope to give you a reference, and I hope you can support developepaer more.

Recommended Today

Hot! Front and rear learning routes of GitHub target 144K

Hello, Sifu’s little friend. I’m silent Wang Er. Last week, while appreciating teacher Ruan Yifeng’s science and technology weekly, I found a powerful learning route, which has been marked with 144K on GitHub. It’s very popular. It covers not only the front-end and back-end learning routes, but also the operation and maintenance learning routes. As […]