El and Ognl contrast

Source: Internet
Author: User
Tags arithmetic arithmetic operators constant logical operators

Transferred from http://newleague.iteye.com/blog/730898

Take a value from the session
<c:out value= "${sessionscope.user.userid}" ></c:out><br>
<c:out value= "${user.userloginname}" ></c:out><br>
<s:property value= "#session. User.userid"/><br>
${session.user.userid}<br>
${sessionscope.user.userid}<br>

Basic syntax  
First, El profile  
1. Syntax structure  
${expression} 
2.[] With the. operator  
EL provides. And [] Two operators to access the data. &NBSP
When you want to access a property name that contains special characters, such as. or? etc. is not a symbol of letters or numbers, you must use []. For example:  
${user. My-name} should be changed to ${user< "My-name" >} 
If you want to dynamically take a value, you can do it with [], and. cannot be dynamically fetched. For example:  
${sessionscope.user} data is a variable  
3. Variable  
El Access variable data is simple, for example: ${username}. It means to remove a variable whose name is username in a range. &NBSP
Because we do not specify which range of username, it is searched sequentially from page, Request, session, application range. &NBSP
If the way to find username, direct return, no longer continue to find, but if all the scope is not found, then return null. &NBSP
The name of the property range in El  
page         pagescope 
Request          requestscope 
session          sessionscope 
application     applicationscope

Second, El implied object
1. Implied objects related to the scope
The El implied object associated with the scope contains the following four: Pagescope, Requestscope, Sessionscope and Applicationscope;
They are basically the same as JSP PageContext, request, session and application;
In El, these four suppressed objects can only be used to obtain the Range property value, that is, getattribute (String name), but no other relevant information can be obtained.

For example: We want to get a value that stores a property username in the session, and you can use the following methods:
Session.getattribute ("username") obtains the value of username,
The following methods are used in El
${sessionscope.username}
2. Implied objects associated with the input
There are two hidden objects associated with the input: param and paramvalues, which are the more specific suppressed objects in El.

For example, when we want to take a user's request parameter, we can use the following methods:
Request.getparameter (String name)
Request.getparametervalues (String name)
In El, you can use both Param and paramvalues to get the data.
${param.name}
${paramvalues.name}
3. Other implied objects

Cookies
JSTL does not provide a cookie-setting action,
For example: To obtain a value in the cookie that has a set name of Usercountry, you can use ${cookie.usercountry} to obtain it.
Header and Headervalues
Header stores data that the user's browser and server use to communicate
For example: To get the version of the user's browser, you can use ${header< "User-agent"}.
In addition, in rare opportunities, it is possible to have different values for the same header name, and you must instead use Headervalues to get the values.
Initparam
Initparam to set the environment parameters for the Web site (context)
Example: General method String UserID = (string) application.getinitparameter ("userid");
You can use ${initparam.userid} to get the name UserID
PageContext
PageContext obtain additional information about the user's requirements or pages.
${pagecontext.request.querystring} Gets the requested parameter string
${pagecontext.request.requesturl} Gets the requested URL, but does not include the requested parameter string
${pagecontext.request.contextpath} The name of the Web application service
${pagecontext.request.method} method to obtain 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} Gets the user's IP address
${pagecontext.session.new} to determine if the session is new
${pagecontext.session.id} Gets the ID of the session
${pagecontext.servletcontext.serverinfo} to obtain service information on the host side
SAN, El operator
1. Arithmetic operators have five: + 、-、 * or $,/or div,%, or mod
2. There are six relational operators: = = or EQ,!= or NE, < or LT, > or GT, <= or LE, >=, or GE
3. Logical operators have three:&& or and, | | Or OR,!, or not
4. There are three other operators: empty operator, conditional operator, () operator
Example: ${empty param.name}, ${a? B:C}, ${a* (B+c)}

Four, El function (functions).
Grammar: Ns:function (arg1, arg2, Arg3 ... argn)
Where NS is the predecessor name (prefix), it must be placed with the predecessor name of the TAGLIB directive
---------------------------------------------
Add:
<%@ taglib prefix= "C" uri= "Http://java.sun.com/jstl/core_rt"%>
Foreach:
<c:foreach items= "${messages}"
Var= "Item"
begin= "0"
End= "9"
step= "1"
Varstatus= "var" >
......
</c:forEach>


Out:
<c:out value= "${logininfo.username}"/>
C:out> outputs the contents of value to the current position, where the Logininfo object is
The Username property value is output to the current position of the page.
${...} is the syntax of expression Language (EL) in JSP2.0. It defines an expression,
The expression can be a constant (as above), or it can be a specific expression (as in a foreach loop body
of the situation). Typical cases are as follows:
? ${logininfo.username}
This indicates the Username property that references the Logininfo object. We can go through "." Operator Primer
Object properties, such as ${logininfo}, can be referenced using the object's properties, or "[]"
has achieved the same effect as ${logininfo.username}.
The meaning of the [] reference method is that if special characters appear in the property name, such as "." Or "-",
You must use ' [] ' to get the value of the property to avoid grammatical conflicts (you should try to avoid it when developing the system)
The emergence of this phenomenon).
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 amount of coding.
Another question that arises here is where EL will find the Logininfo object, for
${logininfo.username} Such an expression, the first is to look up from the current page before the
No variable logininfo is defined, if not found, then to request, session,
Application in the range until found. If we don't find a match until the end
Variable, NULL is returned.
If we need to specify the search scope for a variable, you can specify the search scope in the EL Expression:
${pagescope.logininfo.username}
${requestscope.logininfo.username}
${sessionscope.logininfo.username}
${applicationscope.logininfo.username}
In spring, the result data returned by all the logical processing units will be placed as attributes
To be returned to the HttpServletRequest object (see the spring source code for a specific implementation)
Org.springframework.web.servlet.view.InternalResourceView.
The implementation code for the Exposemodelasrequestattributes method), which means spring
In MVC, the result data object defaults to Requestscope. So, in spring MVC,
The following addressing methods should be used with caution:
${sessionscope.logininfo.username}
${applicationscope.logininfo.username}
? ${1+2}
The result is an expression that evaluates to an integer value of 3.
? ${I&GT;1}
If the value of the variable is i>1, the bool type true is returned. Compared with the above example, El will be found from
Dynamic returns different data types based on the expression evaluation.
Expressions are written in roughly the same way as expressions in Java code.

If/choose:
<c:if test= "${var.index% 2 = 0}" >
*
</c:if>
The judgment condition is generally an El expression.
<c:if> does not provide else clause, it may be inconvenient to use, at this time we can pass the <c:choose>
tag to achieve a similar goal:
<c:choose>
<c:when test= "${var.index% 2 = 0}" >
*
</c:when>
<c:otherwise>
!
</c:otherwise>
</c:choose>
A switch statement similar to Java,<c:choose> provides a simplified approach to complex judgment conditions. Its
The <c:when> clause is similar to a case clause and can occur multiple times. The code above, outputting the "*" number in odd rows,
And even rows output "!".
---------------------------------------------
Further added:
The 1 El expression is represented by ${} and can be used in all HTML and JSP tags to replace the complex Java code in the JSP page.
2 El expressions manipulate constant variables and implicit objects. The most commonly used implicit objects are ${param} and ${paramvalues}. ${param} represents a value that returns a single string in the request parameter. ${paramvalues} represents a set of values that return a request parameter. pagescope represents a variable of a page range. Requestscope represents a variable of the request object. Sessionscope represents a variable within the scope of a session. Applicationscope represents a variable of the scope of the application.
3 <%@ page iselignored= "True"%> indicates whether the El language is disabled, true to prohibit. False indicates that the default enabled El language is not prohibited in. JSP2.0.
4 El language can display logical expressions such as ${true and false} result is false relational expression such as ${5>6} result is false arithmetic expression such as ${5+5} result is 10
The variable search scope in 5 El is: page request session application dot operator (.) and "< >" are values that represent getting variables. The difference is that < > can show the variables of non-speech classes


OGNL
OGNL is the abbreviation of Object Graph navigation language, the detailed related information can refer to: http://www.ognl.org. Here we only cover the basic support for OGNL in the STRUTS2 framework.

OGNL is an object, a query language for attributes. There is a context in the OGNL, called the contexts, in which there is a root element (root), access to the properties of the root element can directly use the property name, but access to other non-root element attributes must be added with a special symbol #.

In Struts2, the context is actioncontext, the root element bit value stack (value stacks, the value stack represents a family object instead of an object, where an instance of the action class also belongs to one of the value stacks). The contents of the Actioncontext are shown below:
|
|--application
|
|--session
Context Map---|
|--value Stack (root)
|
|--request
|
|--parameters
|
|--attr (Searches page, request, session, then application scopes)
|
Because the action instance is placed in the value stack, and the value stack is one of the root elements (root), access to the properties in the action can be without tag #, and all other accesses must use the # tag.

Properties that reference the action
<s:property value= "PostalCode"/>
The properties of other non-root (root) elements in Actioncontext can be accessed in the following manner:
<s:property value= "#session. Mysessionpropkey"/> or
<s:property value= "#session <" Mysessionpropkey ">"/> or
<s:property value= "#request <" Mysessionpropkey ">/>

The action class can use static methods in Actioncontext to access Actioncontext.
Actioncontext.getcontext (). GetSession (). Put ("Mysessionpropkey", mysessionobject);

Ognl and collection (lists,maps,sets)

The syntax for generating a list is: {e1,e2,e3}.
<s:select label= "label" name= "name"
list= "{' name1 ', ' name2 ', ' Name3 '}" value= "%{' name2 '}"/>
The above code generates an HTML select object, which is optional: Name1,name2,name3, and the default value is: Name2.

The syntax for generating a map is: # {key1:value1,key2:value2}.
<s:select label= "label" name= "name"
list= "#{' foo ': ' Foovalue ', ' bar ': ' Barvalue '}"/>
The above code generates an HTML select object, and Foo's name says: Foovalue,bar name is: Barvalue.

Determines whether an object exists in the list:
<s:if test= "' foo ' in {' foo ', ' Bar '}" >
Muhahaha
</s:if>
<s:else>
Boo
</s:else>

<s:if test= "' foo ' not in {' foo ', ' Bar '}" >
Muhahaha
</s:if>
<s:else>
Boo
</s:else>

Get a part of a list:
? – All objects that satisfy the selection logic
^-the first object to satisfy the selection logic
$-the last object that satisfies the selection logic
For example:
Person.relatives. {#this. gender = ' Male '}
The above code obtains all the male (This.gender==male) relatives (relatives) of this person (persons)


Lambda expression

OGNL supports simple lambda expression syntax, which allows you to create simple lambda functions.

For example:
Fibonacci:
If n==0 return 0;
ElseIf n==1 return 1;
else return fib (n-2) +fib (n-1);
FIB (0) = 0
FIB (1) = 1
FIB (11) = 89

How does a ognl lambda expression work?
Lambda expressions must be placed inside square brackets, #this表示表达式的参数. For example:
<s:property value= "#fib =:< #this ==0? 0: #this ==1? 1: #fib (#this-2) + #fib (#this-1), #fib (one) "/>

#fib =:< #this ==0? 0: #this ==1? 1: #fib (#this-2) + #fib (#this-1) > defines a lambda expression,
The expression was called #fib (11).

So the output of the above code is: 89

In JSP2.1 # is used as a special notation for JSP EL (expression language), so the use of OGNL can cause problems,  
A simple way to disable the JSP2.1 EL feature is to modify the Web.xml file:  
<JSP-CONFIG>&NBSP
<jsp-property-group> 
<url-pattern>*.jsp</url-pattern> &NBSP
<el-ignored>true</el-ignored> 
</jsp-property-group> 
</ Jsp-config>

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.