EL expression usage in JSP explained
EL Full name is Expression Language
The EL syntax is simple, and its best feature is that it is easy to use. The main syntactic structures of EL are described next.
${sessionScope.user.sex}
All ELs start with ${ and end with }. The EL example above means that from the scope of the Session, get
Gender of the user. If you follow the previous JSP Scriptlet write up as follows.
User user =(User)session.getAttribute("user");
String sex =user.getSex( );
When comparing the two, you can find that the syntax of EL is more convenient and concise than the traditional JSP Scriptlet.
...with the [ ] operator
EL offers . and [ ] operators to navigate the data. The following two represent the same meaning.
${sessionScope.user.sex} tantamount to${sessionScope.user["sex"]}
.harmony [ ] You can also mix them at the same time, as follows:
${sessionScope.shoppingCart[0].price}
The return result is the price of the first item in the shoppingCart.
However, there will be differences between the two in the following two cases.
(1) Always use [ ] when the name of the attribute to be accessed contains some special characters, such as . or -, which are not letters or numbers.
For example: ${user. My-Name }
The above is not the correct way, Should read:${user["My-Name"] }
(2) Let us consider the following cases.
${sessionScope.user[data]}
this time,data is a variable, in casedata the value of"sex" time, Then the above example tantamount to${sessionScope.user.sex};
in casedata the value of"name" time, It just tantamount to${sessionScope.user.name}。
So, if you want to take values dynamically, you can do it in the same way as above, but. It is not possible to do dynamic fetching.
EL variables
EL Access to variable data is simple, e.g. ${username}. It means to take out the variable with the name username in a certain range.
Since we don't specify which range of username, it defaults to looking at the Page range first, and if it doesn't find it, the
And then in order to the Request, Session, and Application scopes. If you find username on the way, just pass it back and don't look any further.
But if the entire range is not found, null is passed back, and of course the EL expression is optimized to show 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.
model case | instructions |
---|---|
${pageScope.username} | extractPage ambitusername variable |
${requestScope.username} | Fetch the username variable of the Request range |
${sessionScope.username} | Fetch the session-wide username variable |
${applicationScope.username} | Fetch the Application-scoped username variable |
where pageScope, requestScope, sessionScope and applicationScope are all implicit objects of EL.
By their names one can easily guess what they stand for.
For example, ${sessionScope.username} is the username variable that takes out the Session scope. Isn't this a better way of writing the JSP than the previous way of writing.
String username =(String) session.getAttribute("username"); liable (to)、 Much simpler.
Type of automatic transformation
In addition to providing a convenient syntax for accessing variables, another convenient feature of EL is that it automatically transforms types, as shown in the following example.
${param.count + 20}
If a window passescount the value of10 time, Then the above result because of30。 I've never been exposed to it before.JSP of readers may take the above example for granted,
But in JSP 1.2 you can't do this because the values passed from the form are always of type String, so when you receive them, you have to convert them to something else.
e.g. int, float, etc., before some mathematical operations can be performed, here is how it was done before.
String str_count =request.getParameter("count");
int count =Integer.parseInt(str_count);
count = count + 20; So, be careful not to get confused with the java syntax (which converts numbers to strings when strings and numbers are linked with "+").
EL implicit object
JSP have9 size implicit object, but (not)EL It also has its own implicit object。EL implicit object In total, there are11 size
implicit object | types | instructions |
---|---|---|
PageContext | javax.servlet.ServletContext | indicates the PageContext of this JSP |
PageScope | java.util.Map | Get the value corresponding to the property name of the Page range |
RequestScope | java.util.Map | Get the value corresponding to the attribute name of the Request scope |
sessionScope | java.util.Map | obtainSession The value corresponding to the attribute name of the range |
applicationScope | java.util.Map | Get the value corresponding to the property name of the Application scope |
param | java.util.Map | As in ServletRequest.getParameter(String name). Pass back a String type value |
paramValues | java.util.Map | As in ServletRequest.getParameterValues(String name). Pass back a value of type String[] |
header | java.util.Map | As in ServletRequest.getHeader(String name). Pass back a String type value |
headerValues | java.util.Map | as withServletRequest.getHeaders(String name)。 pass backString[] types values |
cookie | java.util.Map | As in HttpServletRequest.getCookies() |
initParam | java.util.Map | As in ServletContext.getInitParameter(String name). Pass back a String type value |
One thing to note though is that if you're outputting a constant with EL, the string should be in double quotes, otherwise EL will treat what you think is a constant as a variable by default.
This outputs null if the variable does not exist in the 4-declaration range, or the value of the variable if it does.
Attribute and Scope
Scope relatedEL implicit object Contains the following four:pageScope、requestScope、sessionScope harmony
applicationScope, They're basically the same asJSP ofpageContext、request、sessionharmonyapplication the same as, So the author here only slightly instructions。
However, it must be noted that these four implicit objects can only be used to obtain the range attribute value, i.e. getAttribute(String name) in JSP, but not other relevant information.
For example: the request object in the JSP can access properties in addition to the user's request parameters or form header information and so on.
But in EL, it would simply be used to get the value of the attribute corresponding to the range
for example: We're going to be insession Storing an attribute in, It is named asusername, (located) atJSP use insession.getAttribute("username") come up withusername values,
In EL, however, it uses ${sessionScope.username} to get its value.
cookie
A so-called cookie is a small text file that records the contents of Session Tracking as a key and value in this text file, which usually exists in the browser's staging area.
The JSTL does not provide the action of setting a cookie, as this action is usually something that the back-end developer must do, rather than leaving it to the front-end developer.
If we set a value in the cookie with the name userCountry, then we can use ${cookie.userCountry} to get it.
header and headerValues
header Stores data used by the user's browser and the server to communicate, When a user requests a server-side page, A header file with the requested information will be sent, for example: Version of the user's browser、 Other relevant data such as the area set by the user's computer。 If you want to get the version of the user's browser, i.e.${header["User-Agent"]}。 Also on the rare occasion, It is possible that the same header name has different values, At this point, you must instead use theheaderValues to get these values。
Note: Because the User-Agent contains the special character "-", you must use "[]" instead of
$(header.User-Agent)。
initParam
Like any other property, we can set the web site's environment parameters (Context) ourselves, and when we want to get these parameters initParam is like any other property
We can set the web site's environment parameters (Context) ourselves, and when we want to get 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 just use ${initParam.userid} to get the parameter with the name userid and the value mike.
Here's how it was done before:String userid =(String)application.getInitParameter("userid");
param and paramValues The following methods are usually used to obtain user parameters.
request.getParameter(Stringname) request.getParameterValues(Stringname)
(located) at EL In the case of the param and paramValues Both to obtain data。 ${param.name} ${paramValues.name}
Here the function of param is the same as request.getParameter(String name), while paramValues and request.getParameterValues(String name) is the same. If the user fills out a form with the form name username, then we can use ${param.username} to get the value the user filled in.
See here, you should be very clear that EL expressions can only take values through the built-in object, that is, read-only operations, if you want to write operations, let the background code to complete, after all, EL expressions are just the output label on the view. pageContext
We can use ${pageContext} to get other details about user requests or pages. The following table lists a few of the more commonly used sections
Expression | instructions |
---|---|
${pageContext.request.queryString} | Get the requested parameter string |
${pageContext.request.requestURL} | Get the URL of the request, but not the parameter string of the request, i.e. the HTTP address of the servlet. |
${pageContext.request.contextPath} | The name of the webapplication that serves |
${pageContext.request.method} | Methods to get HTTP (GET, POST) |
${pageContext.request.protocol} | Obtain the protocol used (HTTP/1.1, HTTP/1.0) |
${pageContext.request.remoteUser} | Get user name |
${pageContext.request.remoteAddr} | Obtain the user's IP address |
${pageContext.session.new} | Determine whether the session is new or not. A new session means that it has just been generated by the server and not yet used by the client. |
${pageContext.session.id} | Get the session ID |
${pageContext.servletContext.serverInfo} | Obtain service information on the host side |
This object can effectively improve the hard-coding problem of code, such as a page with an A tag link to access a SERVLET, if the HTTP address of the SERVLET is written dead
Then if the source code has to be modified when the SERVLET-MAPPING of that SERVLET changes, the maintainability will be greatly reduced.
EL Arithmetic Operations
The expression language supports arithmetic operators and logical operator very many, All the people inJava Arithmetic operators supported in the language, Expression languages can all be used;
evenJava Some arithmetic operators that are not supported by the language and logical operator, Expression languages also support。
Code
<%@pagecontentType="text/html;charset=gb2312"%> <html> <head> <title> expressive language- arithmetic operator</title> </head> <body> <h2> expressive language- arithmetic operator</h2> <hr> <tableborder="1"bgcolor="aaaadd"> <tr> <td><b> expressive language</b></td> <td><b> count result</b></td> </tr> <!-- Direct output constants--> <tr> <td>${1}</td> <td>${1}</td> </tr> <!-- Computational Addition--> <tr> <td>${1.2+2.3}</td> <td>${1.2+2.3}</td> </tr> <!-- Computational Addition--> <tr> <td>${1.2E4+1.4}</td> <td>${1.2E4+1.4}</td> </tr> <!-- Calculating subtraction--> <tr> <td>${-4-2}</td> <td>${-4-2}</td> </tr> <!-- calculate multiplication--> <tr> <td>${21*2}</td> <td>${21*2}</td> </tr> <!-- Computational division--> <tr> <td>${3/4}</td> <td>${3/4}</td> </tr> <!-- Computational division--> <tr> <td>${3div4}</td> <td>${3div4}</td> </tr> <!-- Computational division--> <tr> <td>${3/0}</td> <td>${3/0}</td> </tr> <!-- calculate the remainder--> <tr> <td>${10%4}</td> <td>${10%4}</td> </tr> <!-- calculate the remainder--> <tr> <td>${10mod4}</td> <td>${10mod4}</td> </tr> <!-- Calculating the trinomial operator--> <tr> <td>${(1==2)?3:4}</td> <td>${(1==2)?3:4}</td> </tr> </table> </body> </html>
<%@pagecontentType="text/html;charset=gb2312"%> <html> <head> <title> expressive language- arithmetic operator</title> </head> <body> <h2> expressive language- arithmetic operator</h2> <hr> <tableborder="1"bgcolor="aaaadd"> <tr> <td><b> expressive language</b></td> <td><b> count result</b></td> </tr> <!-- Direct output constants--> <tr> <td>${1}</td> <td>${1}</td> </tr> <!-- Computational Addition--> <tr> <td>${1.2+2.3}</td> <td>${1.2+2.3}</td> </tr> <!-- Computational Addition--> <tr> <td>${1.2E4+1.4}</td> <td>${1.2E4+1.4}</td> </tr> <!-- Calculating subtraction--> <tr> <td>${-4-2}</td> <td>${-4-2}</td> </tr> <!-- calculate multiplication--> <tr> <td>${21*2}</td> <td>${21*2}</td> </tr> <!-- Computational division--> <tr> <td>${3/4}</td> <td>${3/4}</td> </tr> <!-- Computational division--> <tr> <td>${3div4}</td> <td>${3div4}</td> </tr> <!-- Computational division--> <tr> <td>${3/0}</td> <td>${3/0}</td> </tr> <!-- calculate the remainder--> <tr> <td>${10%4}</td> <td>${10%4}</td> </tr> <!-- calculate the remainder--> <tr> <td>${10mod4}</td> <td>${10mod4}</td> </tr> <!-- Calculating the trinomial operator--> <tr> <td>${(1==2)?3:4}</td> <td>${(1==2)?3:4}</td> </tr> </table> </body> </html>
The above page demonstrates the functionality of the arithmetic operators such as addition, subtraction, multiplication, division, and remainder supported by the expression language, and the reader may have also discovered that the expression language also supports operators such as div and mod.
And the expression language treats all values as floating point numbers, consequently3/0 The essence of the3.0/0.0, get result It should be.Infinity。
If you need to output the "$" symbol normally in a page that supports the expression language, add the escape character "" before the "$" symbol, otherwise the system thinks the "$" is a special token for the expression language.
EL Relational Operators
Relational operators | instructions | model case | result |
---|---|---|---|
== or eq | tantamount to | ${5==5} or ${5eq5} | true |
!= or ne | not equal ≠ | ${5!=5} or ${5ne5} | false |
< perhaps lt | less than, < | ${3<5} perhaps${3lt5} | true |
> perhaps gt | more than, > | ${3>5} perhaps{3gt5} | false |
<= perhaps le | less than, < tantamount to | ${3<=5} perhaps${3le5} | true |
>= perhaps ge | more than, > tantamount to | 5} or ${3ge5} | false |
Expression languages can compare not only numbers to numbers, but also characters to characters, and strings are compared in size based on their corresponding UNICODE values. Note: When using the EL relational operator, it cannot be written as. ${param.password1} = =${param.password2} perhaps ${ ${param.password1 } = = ${param.password2 } } Instead, it should be written as ${ param.password1 = =param.password2 }
EL logical operator
logical operator | model case | result |
---|---|---|
&& perhapsand | intersection${A && B} perhaps${A and B} | true/false |
|| or | The concurrent set ${A || B} or ${A or B} | true/false |
! or not | Not ${! A } or ${not A} | true/false |
Empty operator
The Empty operator is mainly used to determine whether a value is empty (NULL, empty string, empty collection).
conditional operator
${ A ? B : C}