EL and OGNL

Source: Internet
Author: User

<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 1. EL Introduction 1. syntax structure $ {expression} 2. [] and. the EL operator provides. and [] operators 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 []. Example: $ {user. change My-Name} to $ {user ["My-Name"]}. to dynamically set the value, use. dynamic values cannot be achieved. For example, in $ {sessionScope. user [data]}, data is a variable. 3. The method for variable EL to access variable data is simple, for example, $ {username }. It means to retrieve the variable named username in a range. Because we do not specify the username of the range, it will search for the range from Page, Request, Session, and Application in sequence. If the username is found on the way, it will be directly returned and will not be found any more, but if all the ranges are not found, null will be returned. Name of attribute range in EL Page pagination Request RequestScope Session SessionScope Application ApplicationScope 2. EL implicit object 1. scope-related implied objects EL-dependent scope objects 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 obtain other related information. For example, to obtain the value of username in the session attribute, you can use the following method: session. getAttribute ("username") gets the value of username. In EL, use the following method $ {sessionScope. username} 2. input-related implicit objects include param and paramValues, which are especially implicit objects in EL. For example, to obtain user request parameters, you can use the following method: request. getParameter (String name) request. in EL, getParameterValues (String name) can use param and paramValues to obtain data. $ {Param. name }$ {paramValues. name} 3. the other implicit object cookie JSTL does not provide the cookie setting action. For example, to obtain a value with the userCountry name in the cookie, you can use $ {cookie. userCountry. Header and headerValues header store the data for communication between the User's browser and the server. To obtain the version of the User's 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 these values. InitParam obtains the environment parameter (Context) of the Set web site. For example, the general method is String userid = (String) application. getInitParameter ("userid"); $ {initParam. userid. $ {PageContext. request. queryString} gets the request parameter string $ {pageContext. request. requestURL} retrieves the request URL, but does not include the request parameter string $ {pageContext. request. contextPath} Name of the Service's web application $ {pageContext. request. method} get http method (GET, POST) $ {pageContext. request. protocol} obtained 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} judge whether the session is new $ {PageContext. session. id} gets the session ID $ {pageContext. servletContext. serverInfo} obtains the service information of the host. 3. EL operator 1. there are five Arithmetic Operators: +,-, * or $,/or div, %, or mod 2. there are six Relational operators: =, eq, and ,! = Or ne, <or lt,> or gt, <= or le,> =, or ge 3. logical operators include: & and, | or ,! Or not 4. There are three other operators: Empty operator, conditional operator, and () operator example: $ {empty param. name}, $ {? B: C}, $ {A * (B + C)} 4. EL functions (functions ). Syntax: ns: function (arg1, arg2, arg3 .... ArgN) Where ns is the prefix, which must be set to the prefix of the taglib command -----------------------------------------------------. Supplement: java code <% @ 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} "/> [java] <% @ 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 content in the value to the current location. Here, the username attribute value of the logininfo object is output to the current location of the page. $ {......} Is the Expression Language (EL) syntax in JSP2.0. It defines an expression, where the expression can be a constant (as above) or a specific expression Statement (such as in the forEach loop body ). A typical case is as follows :? $ {Logininfo. username} indicates that the username attribute of the logininfo object is referenced. We can you can also use the [] operator to reference object attributes, such as $ {logininfo [username]} and $ {logininfo. username} achieves the same effect. "[]" Indicates that if the attribute name contains special characters, such as ". "or"-", you must use" [] "to obtain the attribute value to avoid syntax conflicts (this phenomenon should be avoided 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 (); we can see that EL greatly saves the encoding capacity. Another problem that is raised here is where EL will find the logininfo object, for $ {logininfo. for expressions such as username}, the logininfo variable is first defined on the current page. If the variable is not found, the variable is searched in the range of Request, Session, and Application until it is found. If no matching variable is found until the end, null is returned. if you need to specify the search range of the variable, you can specify the search range in the EL expression: Java code $ {pagination. logininfo. username }$ {requestScope. logininfo. username }$ {sessionScope. logininfo. username }$ {applicationScope. logininfo. username} [java] $ {pagination. 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 an Attribute in Htt PServletRequest object (for specific implementation, see org. springframework. web. servlet. view. internalResourceView. exposeModelAsRequestAttributes method implementation Code). In SpringMVC, results 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 }? The result of ${1 + 2} 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 automatically returns different data types based on the expression calculation results. Expressions are written in roughly the same way as expressions in java code. Java code IF/CHOOSE: <c: if test = "$ {var. index % 2 = 0}"> * </c: if> [java] view plaincopyprint? IF/CHOOSE: <c: if test = "$ {var. index % 2 = 0}"> * </c: if> the condition is generally an EL expression. <C: if> the else clause is not provided, which may be inconvenient to use. In this case, we can use the <c: choose> tag to achieve a similar purpose: Java code <c: choose> <c: when test = "$ {var. index % 2 = 0} "> * </c: when> <c: otherwise>! </C: otherwise> </c: choose> [java] <c: choose> <c: when test = "$ {var. index % 2 = 0} "> * </c: when> <c: otherwise>! </C: otherwise> </c: choose> similar to the switch statement in Java, <c: choose> provides a simplified processing method under complex conditions. The <c: when> clause is similar to the case clause and can appear multiple times. The above code outputs "*" in an odd number of rows and "!" in an even number of rows. ------------------------------------------- Supplement: 1 EL expression is represented by $ {}. It can be used in all HTML and JSP tags to replace the complex JAVA code on JSP pages. 2 EL expressions can operate on constant variables and implicit objects. the most common implicit objects are $ {param} and $ {paramValues }. $ {param} indicates the value of a single string in the request parameters. $ {paramValues} indicates that a group of values of the request parameters are returned. pagination indicates a variable in the page range. requestScope indicates the variable of the request object. sessionScope indicates the variables in the session range. applicationScope indicates the application range variable. 3 <% @ page isELIgnored = "true" %> indicates whether the EL language is disabled. TRUE indicates that the EL language is disabled. FALSE indicates that it is not prohibited. the default EL language is enabled in jsp2.0. 4 EL language display logic Expression $ {true and false} results in a false relational expression. For example, $ {5> 6} results in a false arithmetic expression. For example, ${5 + 5} results in a Variable Search of 10 5 EL. the range is: page request session application vertex operator (.) and "[]" indicate the value of the variable. the difference is [] can display non-word class variable OGNL is the abbreviation of Object Graph Navigation Language, detailed information can refer to: http://www.ognl.org. Here we only involve the basic support for ognl in the Struts2 framework. OGNL is an object and a query language for attributes. In OGNL, there is a Context (called Context) of Map type. In this Context, there is a root element (root). To access the attributes of the root element, you can directly use the attribute name, however, special characters # Must be added for access to other non-root element attributes #. In Struts2, the context is ActionContext, and the root element bit Value Stack (Value Stack, Value Stack represents a family of objects rather than an object, and the Action class instance also belongs to a Value Stack ). The content in ActionContext is as follows: | -- 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, therefore, you can use the # flag for access to the attributes in the Action, but the # flag for other accesses. Reference the Action attribute <s: property value = "postalCode"/> other non-root attributes in ActionContext can be accessed as follows: Java code <s: property value = "# session. mySessionPropKey "/> or <s: property value =" # session ["mySessionPropKey"] "/> or <s: property value = "# request [" mySessionPropKey "]/> [java] <span style =" color: # ff0000; "> <s: property value =" # session. mySessionPropKey "/> or <s: property value =" # session ["mySessionPropKey"] "/> or <s: proper Ty value = "# request [" mySessionPropKey "]/> </span> the Action class can use static methods in ActionContext to access ActionContext. Java code ActionContext. getContext (). getSession (). put ("mySessionPropKey", mySessionObject); [java] <span style = "color: # ff0000;"> ActionContext. getContext (). getSession (). put ("mySessionPropKey", mySessionObject); </span> the syntax of the List generated by OGNL and Collection (Lists, Maps, Sets) is {e1, e2, e3 }. java code <s: select label = "label" name = "name" list = "{'name1', 'name2 ', 'name3'} "value =" % {'name2'} "/> [java] <span style =" color: # ff00 00; "> <s: select label =" label "name =" name "list =" {'name1', 'name2 ', 'name3'} "value =" % {'name2'} "/> </span> the preceding Code generates an HTML Select object. The optional content is name1, name2, name3; default value: name2. Syntax for generating Map: # {key1: value1, key2: value2 }. java code <s: select label = "label" name = "name" list = "# {'foo': 'foovalue', 'bar ': 'barvalue'} "/> [java] <span style =" color: # ff0000; "> <s: select label = "label" name = "name" list = "# {'foo': 'foovalue', 'bar ': 'barvalue'} "/> </span> the code above generates an HTML Select object. The foo name indicates foovalue, and the bar name indicates barvalue. Determine whether an object exists in the List: Java code <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> [java] <span style =" color: # ff0000; "> <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> </span> gets a part of a List :? -All objects meeting the selection logic ^-the first object meeting the selection logic $-the last object meeting the selection logic, for example, Java code person. relatives .{? # This. gender = 'male'} [java] <span style = "color: # ff0000;"> person. relatives .{? # This. gender = 'male'} </span> the above Code gets this person (person) All male (this. gender = male) relatives Lambda expressions OGNL supports Simple Lambda expression syntax, which can be used to create simple lambda functions. Example: Java code MAID: 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 [java] <span style = "color: # ff0000;"> MAID: 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 </span> How does OGNL's Lambda expression work? Lambda expressions must be placed inside square brackets. # this indicates the parameters of the expressions. Example: Java code <s: property value = "# fib =: [# this = 0? 0: # this = 1? 1: # fib (# this-2) + # fib (# this-1)], # fib (11) "/> # fib =: [# this = 0? 0: # this = 1? 1: # fib (# this-2) + # fib (# this-1)] defines a Lambda expression. # fib (11) calls this expression. [Java] <span style = "color: # ff0000;"> <s: property value = "# fib =: [# this = 0? 0: # this = 1? 1: # fib (# this-2) + # fib (# this-1)], # fib (11) "/> # fib =: [# this = 0? 0: # this = 1? 1: # fib (# this-2) + # fib (# this-1)] defines a Lambda expression. # fib (11) calls this expression. </Span> therefore, the output of the above Code is as follows: 89 in JSP2.1 # It is used as a special note of jsp el (Expression Language). Therefore, the use of OGNL may cause problems, A simple method is to disable the EL feature of JSP2.1, which requires modifying the web. xml file: Java code <jsp-config> <jsp-property-group> <url-pattern> *. jsp </url-pattern> <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.