Application of EL expressions in JSP and common methods
EL expression
1. EL Introduction
1) syntax structure
${expression}
2) [] and. Operator
EL provides two operators:. and [] to access data.
When the attribute name to be accessed contains some special characters, such as. Or? If it is not a letter or number, you must use [].
For example:
$ {User. My-Name} should be changed to $ {user [My-Name]}
If you want dynamic values, you can use [] instead of dynamic values. For example:
Data in $ {sessionScope. user [data]} is a variable.
3) variables
EL is easy to access variable data, for example, $ {username }. It means that the name in a certain range is called
Username variable.
Because we do not specify the username range, it will start from Page, Request, Session,
Application range search.
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,
Return null.
Name of attribute range in EL
Page PageScope
Request RequestScope
Session SessionScope
Application ApplicationScope
4) The 1--EL expression is represented by $ {}. It can be used in all HTML and JSP tags to replace the complex JAVA code in JSP pages.
2--EL expressions can operate constant variables and implicit objects. The most common implicit objects include $ {param} and $ {paramValues }.
$ {Param} indicates the value of a single string in the returned Request Parameters. $ {paramValues} indicates a group of returned request parameters.
Value. pagination indicates the variable in the page range. requestScope indicates the variable in the request object. sessionScope indicates the session
The variable in the range. applicationScope indicates the variable in the scope of the application.
3 -- <% @ page isELIgnored = true %> indicates whether the EL language is disabled. TRUE indicates that the EL language is disabled. FALSE indicates that the EL language cannot be disabled.
. The default EL language is enabled in jsp2.0.
4 -- the EL language can display logical expressions. For example, $ {true and false}. The result is a false relational expression. For example, if $ {5> 6} is closed
If it is a false arithmetic expression, for example, ${5 + 5}, the result is 10.
The search range of variables in 5--EL is: page request session application vertex operator (.) and [] are both
Returns the value of a variable. The difference is that [] can display non-word class variables.
2. EL implicit object
1) implied objects related to the scope
The EL implied objects related to the scope include the following four: pagination, requestScope, sessionScope, and
applicationScope;
They are basically the same as pageContext, request, session, and application of JSP;
In EL, the four implicit objects can only be used to obtain the range attribute value, that is, getAttribute (String name), but cannot be obtained.
Other information.
For example, to obtain the value of the username attribute stored in the session, you can use the following methods:
Session. getAttribute (username) gets the value of username,
Use the following method in EL:
${sessionScope.username}
2) hidden objects related to input
There are two implicit objects related to input: param and paramValues, which are special hidden objects in EL.
For example, to obtain user request parameters, you can use the following methods:
request.getParameter(String name)
request.getParameterValues(String name)
In EL, you can use param and paramValues to obtain data.
${param.name}
${paramValues.name}
3. Other hidden objects
1)cookie
JSTL does not provide the cookie setting action,
For example, to obtain a value named userCountry in the cookie, use $ {cookie. userCountry }.
Obtain it.
2) header and headerValues
The header stores the data used by the browser and server for communication.
For example, to obtain the version of your browser, use $ {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 the value.
These values.
3)initParam
InitParam gets the Context parameter for setting the web site)
For example, the general method is String userid = (String) application. getInitParameter (userid );
You can use $ {initParam. userid} to obtain the userid name.
4)pageContext
PageContext obtains other details about user requirements or pages.
$ {PageContext. request. queryString} gets the request parameter string
$ {PageContext. request. requestURL} retrieves the request URL, excluding the request parameter string
$ {PageContext. request. contextPath} indicates the name of the web application of the service.
$ {PageContext. request. method} GET the HTTP method (GET, POST)
$ {PageContext. request. protocol} gets the used protocol (HTTP/1.1, HTTP/1.0)
$ {PageContext. request. remoteUser} obtains the user name
$ {PageContext. request. remoteAddr} obtains the user's IP address
$ {PageContext. session. new} checks whether the session is new.
$ {PageContext. session. id} obtains the session ID.
$ {PageContext. servletContext. serverInfo} obtains the service information of the host.
4) condition tag>
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. There are three logical operators: & and, | or ,! Or not
4. Other operators include Empty, conditional, and ().
Example: $ {empty param. name}, $ {? B: C}, $ {A * (B + C )}
5) EL functions (functions)
Syntax: ns: function (arg1, arg2, arg3 .... ArgN)
Ns is the prefix, which must be the prefix of the taglib command.
6) supplement:
<%@ taglib prefix=c http://java.sun.com/jstl/core_rt>http://java.sun.com/jstl/core_rt %>
FOREACH:
var=item
begin=0
end=9
step=1
varStatus=var>
……
OUT:
C: out> output the content in the value to the current position. Here, the content of the logininfo object
The username attribute value is output to the current position of the page.
$ {......} Is the Expression Language (EL) syntax in JSP2.0. It defines an expression,
The expression can be a constant (as shown above) or a specific expression Statement (such as in the forEach loop body ).
). Typical cases are as follows:
? ${logininfo.username}
This indicates that the username attribute of the logininfo object is referenced. We can use the "." operator to reference
You can also use "[]" to reference object attributes, for example, $ {logininfo [username]}.
The same effect is achieved with $ {logininfo. username.
"[]" Indicates that if the attribute name contains special characters, such as "." or "-",
In this case, you must use "[]" to obtain the attribute value to avoid syntax conflicts (avoid 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 encoding capacity.
Another problem that is raised here is where EL will find the logininfo object.
For expressions such as $ {logininfo. username },
The variable logininfo is negative. If no value is found, the Request, Session,
Search within the Application range until it is found. If the matched
Return null.
If you need to specify the search range of the variable, you can specify the search range in the EL expression:
${pageScope.logininfo.username}
${requestScope.logininfo.username}
${sessionScope.logininfo.username}
${applicationScope.logininfo.username}
In Spring, the result data returned by all logical processing units will be placed as the Attribute
Return to the HttpServletRequest object (for specific implementation, see Spring source code .)
org.springframework.web.servlet.view.InternalResourceView.
Implementation Code of the exposeModelAsRequestAttributes method), that is, Spring
In MVC, The result data objects are requestScope by default. Therefore, in Spring MVC,
The following addressing methods should be used with caution:
${sessionScope.logininfo.username}
${applicationScope.logininfo.username}
? ${1+2}
The result is the expression calculation result, that is, the integer 3.
? ${i>1}
If the variable value is I> 1, return the bool type true. Compared with the previous example, we can find that EL will
Returns different data types based on the calculated results of the expression.
Expressions are written in roughly the same way as expressions in java code.
IF / CHOOSE:
*
The condition is generally an EL expression.
The else clause is not provided. It may be inconvenient to use.
Tag to achieve a similar purpose:
*
!
Similar to the switch statement in Java,
Provides a simplified processing method under complex conditions. Its
Medium
A clause is similar to a case clause and can appear multiple times. The above code outputs the "*" number in an odd number of rows,
The output is "!" in an even row.
Experience: 1. If the EL expression cannot be parsed:-<% @ page isELIgnored = false %>
I. JSTL
1. EL operator>;
2) var specifies the variable and assigns the EL operation result to the variable value true/false;
3) scope: Specifies the range of var variables;
6. Iteration tag
Syntax:
end=”int” step=“int” >
// Loop body
Description: 1) items: a set. It uses an EL expression;
2) var: variable name, which stores items
3) varStatus: variable that shows the cyclic status
① Index: starts from 0;
② Count: element position, starting from 1;
③ First: true is displayed for the first element;
④ Last: true is displayed for the last element;
4) begin: the initial value of the loop (integer );
5) end: the end of the loop;
6) step: The step size and the value of the cycle interval;
7,
Tag
Example:
If the user. wealthy value is true, the user. wealthy is true.
user.generous is true.
user.stingy is true.
user.generous and user.stingy are false.
Note: user. generous is true is displayed only when the condition user. generous returns true.
User. stingy is true only when the return value of condition user. stingy is true.
All other cases (that is, the values of user. generous and user. stingy are not true) show user. generous and
user.stingy are false.
Because JSTL is not like if (){...} Else {...} So this form of statements can only use
,
And
Tag.
8. c: forTokens> tag
Note:
Items that are cyclic by items are none
Delims Delimiter is none
Begin start condition no 0
End condition no last project in the Set
Step No 1
Var indicates whether the variable name of the current project is none
VarStatus: whether the variable that shows the cyclic status is none
Example:
This label is equivalent to the java. util. StringTokenizer class. Here, the string a: B: c: d is separated and cyclically repeated four times,
Token is the string that is split to the current loop.
9,
Tag
Note: The tag redirects the request to another page. It has the following attribute attributes to describe whether the default value is required.
The url address is none.
Context/followed by the name of the Local web Application No current application
Example:
http://www.yourname.com/login.jsp/>
Redirect requests to the http://www.yourname.com/login.jsppage, equivalent to response.setredirect
(http://www.yourname.com/login.jsp);
10,
Tag
Note:
A tag is used to pass a parameter to a redirection or contain page. It has the following attribute Attributions to indicate whether
Required Default Value
The variable name set in the request parameter is none.
Whether the variable value set by value in the request parameter is null
Example:
Pass Parameter 888 with id as the name to the login. jsp page, which is equivalent to login. jsp? Id = 888
11,
Format tags
(Need to import <% @ taglib prefix = fmt http://java.sun.com/jsp/jstl/fmt> http://java.sun.com/jsp/jstl/fmt %>
1) format the date
Value: The Date Value obtained through the EL expression or <% new Date () %>;
Pattern: the output date format;
2) format a number
value=${n} pattern=###,###.## />
Common Methods:
Substring to obtain the substring $ {fn: substring (zip, 6,-1)} The string operations in JSTL are as follows: contains search to determine whether the string contains another string
ContainsIgnoreCase determines whether the string contains another string (case-insensitive)
EndsWith determines whether the string ends with another string
EscapeXml converts some characters to XML Representation. For example, the <character should be converted to <$ {fn: escapeXml (param: info)} indexOf position where the substring appears in the parent string $ {fn: indexOf (name,-)} join combines the data in the array into a new string, and uses the specified character lattice to open $ {fn: join (array ,;)} length gets the length of the string, or the size of the array $ {fn: length (shoppingCart. products)} replace the specified character in the string $ {fn: replace (text ,-,?)} Split splits the string according to the specified character $ {fn: split (customerNames,;)} startsWith to determine whether the string starts with a substring
Substring get substring $ {fn: substring (zip, 6,-1)} substringAfter get substring starting from position of a character $ {fn: substringAfter (zip ,-)} substringBefore: Get the substring $ {fn: substringBefore (zip,-)} toLowerCase to lowercase $ {fn. toLowerCase (product. name)} convert toUpperCase to uppercase characters $ {fn. upperCase (product. name)} trim removes spaces before and after the string $ {fn. trim (name )}