Use of El Expressions in JSP

Source: Internet
Author: User
Tags access properties arithmetic operators logical operators

Lin Bingwen Evankaka original works. Reprint please specify the source Http://blog.csdn.net/evankaka
1. What is EL ELis aJSPexpression Language, full name isExpressionlanguage, usingELThe aim is to simplify theJSPin the way of accessing variables, simple staticHTMLwith theJavathe coupling of the code.
Let's take a look at an example:
<%@ page language= "java" contenttype= "text/html; Charset=iso-8859-1 "    pageencoding=" Iso-8859-1 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
The following are written in El:
<%@ page language= "java" contenttype= "text/html; Charset=iso-8859-1 "    pageencoding=" Iso-8859-1 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

The code is a lot less, and very clear.
2. The JSP EL expression is used for the following situations static Textstandard tags and custom labelsInstallation Supportservlet2.4/jsp2.0of theContainer3. Basic Syntax Format

${EL Expression}

Example:${"Helloworld"}//Output String Constants${ Str }  //Output String VariableStrthe value${3 + 2}//Output3+2the results${User.Name}//OutputUserobject thatnameProperties${user["name"]}//Ibid .${ Sessionscope["User"].name} //Ibid .${user.name}Accessing ObjectsUserof theGetName()method to getnamethe value of the member. ${list[1]}AccessListthe second item of the object. ${map["key"]}AccessMapSpecifies the value of the key.
Let's look at an example.

El's syntax is simple, his biggest feature is the use of very convenient
Cases:

${sessionscope.user.sex}
all El are beginning with ${and ending with}.
The El example above means that the user's gender is obtained from the session. If you use the JSP code before the following syntax:
<% User user = (user) Session.getattribute ("User"); String sex = User.getsex (); %>
compared with the two, El's syntax can be found to be more convenient and concise than the traditional JSP code.

El provides. and [] Two operators to access the data, [] can access the collection or the elements of the array, the attributes of the bean. The following two represent the same meaning, but it is necessary to ensure that the property of the object to be obtained has the corresponding setxxx () and GetXXX () methods.

Cases:

${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.

4, "." with the [] " the same points and differences can access objects with properties. difference:When the name of the property contains a space, a dot, and other complex symbols. Use the. "to access an object that has properties will appear an exception5. OperatorArithmetic Operators(+,-,*,/,%)logical Operators(&&,| |,!orAnd,or,not)XMLoperatorLT  <le<=GT   >GE  >=comparison Operators(>,>=,<,<=,==,!==)-data types can be converted automaticallynull operator(empty)//Duty isNULLWhen you returntrue

The arithmetic operators of 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 operators

Relational operator Description Example results
= = or EQ | equals |${5 = 5} or ${5 eq 5} | True
! = or NE | Not equal to |${5! = 5} or ${5 ne 5} | False
< or 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 | Greater than or equal to |${3 >= 5} or ${3 ge 5} | False


6. Collection AccessArray Access

${} //such as Request.getattribute ("name");

ListAccessMapAccess
7. Implicit Objects

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





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


param

Paramvalues

Header

Headervalues

Terminology Definition

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

Cookies Maps the cookie name to a single Cookie object. A client request to the server can obtain one or more cookies. Expression ${cookie.name.value} returns the first cookie value with a specific name. If the request contains more than one cookie with the same name, the ${headervalues.name} expression should be used.
Initparam The context initialization parameter name is mapped to a single value (obtained by calling Servletcontext.getinitparameter (String name).

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


Pagescope

Requestscope

Sessionscope

Terminology Definition


$sessionScope. NAME}&NBSP;

Applicationscope

Maps application-scoped variable names to their values. The implicit object allows access to application-scoped objects


Special Note:

Cookies Object

The so-called Cookie is a small text file, it is a key, value in the way the contents of the sessiontracking is recorded in this text file, this text file is usually found in the browser's staging area. JSTL does not provide a cookie-setting action, because this action is usually something that the backend developer has to do, rather than handing it over to the front-end developer. If we set a value in the cookie named Usercountry, then we can use ${cookie.usercountry} to get it.

headers and headervalues (Request header Object)
The header stores the data that the user's browser and the server use to communicate, and when the user requests the Web page of the server, it sends out a header file that records the requested information, such as the version of the user's browser, the area set by the user's computer, and other relevant data. If you want to get the version of the user's browser, ${header["User-agent"}. In addition, under rare opportunities, it is possible that the same header name has different values, and you must instead use Headervalues to obtain these values.
Note: Because user-agent contains "-" This special character, you must use "[]" instead of ${header. User-agent}.
Initparam
Just like other properties, we can set our own environment parameters (context) of the Web application, and when we want to get these parameters, we can use the Initparam implicit object to get it, for example: when we set the following in XML:

<?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 use ${initparam.userid} directly to get the name UserID, whose value is Mike's argument. Here is the previous procedure: String userid = (string) application.getinitparameter ("userid");

PageContext Object

We can use ${pagecontext} to get additional details about user requirements or pages. Some of the more commonly used sections are listed below.
Expression description
${pagecontext.request} | Get Request Object
${pagecontext.session} | Get Session Object
${pagecontext.request.querystring} | Gets the requested argument string
${pagecontext.request.requesturl} | Gets the requested URL, but does not include the request's argument string
${pagecontext.request.contextpath} | The name of the Web application of 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} | Determine if the session is a new, so-called new session, indicating that the client has not yet been created by the server
${pagecontext.session.id} | Get the session ID
${pagecontext.servletcontext.serverinfo}| access to host-side service information

8. Special emphasis1. Note that when an expression references one of these objects by name, the corresponding object is returned instead of the corresponding property. For example, if an existing PageContext property contains some other value, ${pagecontext} also returns the PageContext object.

2, note <%@ pageiselignored= "true"%> indicates whether the El language is disabled, true to prohibit. False indicates that the. JSP2.0 enabled El language is not suppressed.

Copyright NOTICE: This article for Bo Master Lin Bingwen Evankaka original article, without Bo Master permission not reproduced.

Use of El Expressions in JSP

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.