EL expression tutorial

  1, EL expression


Full name of EL expression: Expression Language
EL expression function: replace the expression script in JSP page to output data
EL expressions are much simpler than JSP expression scripts
The format of EL expression is ${expression}. Note: EL expression is written in jsp page. The expression is generally the key of domain object
Code demonstration: create Test.jsp in the web directory

<body>
    <%
        request.setAttribute("key", "value");        
    %>
    <%--  Expression script output key1 Value of  --%>
    <%=request.getAttribute("key1")%>
    <%--  EL Expression output key1 Value of  --%>
    ${key1}
    <%--  Expression script output null The page displays when the value is null
          EL Expression output null Value, the page displays nothing(Empty string)--%>
</body>

Operation results:

2, The order in which EL expressions search for domain data


EL expressions are mainly used to output the data in domain objects. When four domain objects have the same key value, EL expressions will search from small to large according to the range of the four domain objects, and output when found, regardless of the order in which the four domain objects are declared

Code demonstration: create Test.jsp in the web directory

<body>
    <%                              
        //Save the same key value to all four domain objects
        request.setAttribute("key", "request");
        session.setAttribute("key", "session");
        application.setAttribute("key", "application");
        pageContext.setAttribute("key", "pageContext");
    %>
    <%--  use EL Expression output key Value of  --%>
    ${key}
</body>


Operation results:


3, EL expressions output properties of Java classes

 
Code demonstration: creating the Person class

public class Person {
    //Output the common attributes, array attributes, list collection attributes and map collection attributes in the Person class
    private String name;
    private String[] phones;
    private List<String> cities;
    private Map<String, Object> map;
    //Note: the age attribute is not declared
    public int getAge() {
        return 18;
    }
    //And all parameter and empty parameter constructors, getter/setter methods of each attribute
}



Code demonstration: create Test.jsp in the web directory

<body>
    <%
        Person person = new Person();
        person.setName("JayChou");
        person.setPhones(new String[]{"123","456","789"});
        //Assign a value to the cities property
        List<String> cities = new ArrayList<String>();
        cities.add("Beijing");
        cities.add("Shanghai");
        cities.add("Shenzhen");
        person.setCities(cities);
        //Assign a value to the map attribute
        Map<String,Object> map = new HashMap<>();
        map.put("key1","value1");
        map.put("key2","value2");
        map.put("key3","value3");
        person.setMap(map);
        pageContext.setAttribute("p", person);
    %>
    <%--EL Object name in expression.The property name does not find the value of the property, but the value corresponding to the name getXxx Method, without which an error will be reported--%>
    output Person: ${ p }<br/>
    output Person of name Properties: ${p.name} <br>
    output Person of phones Array address value: ${p.phones} <br>
    output Person of phones Array property value: ${p.phones[2]} <br>
    output Person of cities Element values in collection: ${p.cities} <br>
    output Person of List Individual element values in the collection: ${p.cities[2]} <br>
    output Person of Map aggregate: ${p.map} <br>
    output Person of Map A in the collection key Value of: ${p.map.key1} <br>
    <%-- Note that even if not age Property, but because there are getAge Method, the results can also be obtained --%>
    output Person of age Value: ${p.age} <br>
</body>


Operation results:

 


4, Operation of EL expression


Syntax: ${operation expression}, EL expression supports the following operators:

1. Relational operation

2. Logical operation

3. Arithmetic operation

4. empty operation
Empty operation can judge whether a data is empty. If it is empty, it will output true. If it is not empty, it will output false
The following cases are empty (empty keyword is added before the original key):
(1) Value is null, empty string
(2) The value is an array of Object type and the length is 0 (Note: the value of other types of arrays with length of 0 is non empty)
(3) The number of list and Map collection elements is 0

5. Ternary operation


Expression 1? Expression 2: expression 3
If expression 1 is true, it returns the value of expression 2, and if expression 1 is false, it returns the value of expression 3

Code demonstration: create Test.jsp in the web directory

<body>
    <%
        //1. When the value is null
        request.setAttribute("emptyNull", null);
        //2. When the value is an empty string
        request.setAttribute("emptyStr", "");
        //3. The value is an array of Object type. When the length is zero
        request.setAttribute("emptyArr", new Object[]{});
        //4. list collection, the number of elements is zero
        List<String> list = new ArrayList<>();
        request.setAttribute("emptyList", list);
        //5. map collection, the number of elements is zero
        Map<String,Object> map = new HashMap<String, Object>();
        request.setAttribute("emptyMap", map);
        //6. Other types of arrays have a length of 0
        request.setAttribute("emptyIntArr", new int[]{});
    %>
    ${ empty emptyNull } <br/>
    ${ empty emptyStr } <br/>
    ${ empty emptyArr } <br/>
    ${ empty emptyList } <br/>
    ${ empty emptyMap } <br/>
    ${ empty emptyIntArr} <br/>
    <%-- Ternary operation   --%>
    ${ 12 != 12 ? "equal":"Unequal" }
</body>


Operation results:


6. "."Point operation sum“[ ]"Bracket operation
 Point operation can output the value of an attribute of an object(getXxx or isXxx Method)
Bracket operation can output the value of an element in an ordered set

Note: bracket operation can be output Map In collection key Containing special characters key Value of

Code demonstration: in web Create under directory Test.jsp

<body>
    <%
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("a.a.a", "aaaValue");
        map.put("b+b+b", "bbbValue");
        map.put("c-c-c", "cccValue");
        request.setAttribute("map", map);
    %>
    <%--special key You need to get rid of the beginning"."And use square brackets and single quotes(Double quotation mark)wrap up--%>
    ${ map['a.a.a'] } <br> <%--Without brackets, it is equivalent to three.operation--%> //The wrong is ${map.a.a.a}
    ${ map["b+b+b"] } <br> <%--Without brackets, it is equivalent to three+operation--%>
    ${ map['c-c-c'] } <br> <%--Without brackets, it is equivalent to three-operation--%>
</body>


Operation results:

 
5, 11 implicit objects of EL expression

The 11 implicit objects in the EL expression are defined by the EL expression itself and can be used directly

EL The 11 implied objects in the expression are EL It is defined in the expression and can be used directly.
	variable 							type 						effect
pageContext 					PageContextImpl 		It can get jsp Nine built-in objects in
pageScope	 					Map<String,Object> 		It can get pageContext Data in domain
requestScope 					Map<String,Object> 		It can get Request Data in domain
sessionScope 					Map<String,Object> 		It can get Session Data in domain
applicationScope 				Map<String,Object> 		It can get ServletContext Data in domain
param 							Map<String,String> 		It can get the value of the request parameter
paramValues 					Map<String,String[]> 	It can also obtain the value of the request parameter, which can be used when obtaining multiple values.
header 							Map<String,String> 		It can get the information of the request header
headerValues 					Map<String,String[]> 	It can get the information of the request header, and it can get multiple values
cookie 							Map<String,Cookie> 		It can get the current request Cookie information
initParam 						Map<String,String> 		It can be obtained in web.xml Configured in<context-param>Context parameters

(1) Use of pagescope, requestScope, sessionScope, applicationScope objects

Code demonstration: create Test.jsp in the web directory

<body>
    <%
        pageContext.setAttribute("key1", "pageContext1");
        pageContext.setAttribute("key2", "pageContext2");
        request.setAttribute("key2", "request");
        session.setAttribute("key2", "session");
        application.setAttribute("key2", "application");
    %>
    <%--  Get properties in a specific domain  --%>
    ${ pageScope.key1 } <br>
    ${ applicationScope.key2 }
    <%--  If directly obtained key1 or key2 It is still retrieved from small to large according to the previous range, and the specified domain cannot be obtained  --%>
</body>

Operation results:

 

(2) Use of pagecontext object

Code example: create Test.jsp in the web directory

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%-- First pass pageContext Object acquisition request,session Object, and then get the following --%>
    <%--
        Get the requested protocol: request.getScheme()
        Get the requested server ip Or domain name: request.getServerName()
        Get the requested server port number: request.getServerPort()
        Get current project path: request.getContextPath()
        How to get the request: request.getMethod()
        Get client's ip Address: request.getRemoteHost()
        Get the unique ID of the session: session.getId()
    --%>
1.agreement: ${ pageContext.request.scheme }<br>
2.The server ip: ${ pageContext.request.serverName }<br>
3.Server port: ${ pageContext.request.serverPort }<br>
4.Get project path: ${ pageContext.request.contextPath }<br>
5.Get request method: ${ pageContext.request.method }<br>
6.Get client ip Address: ${ pageContext.request.remoteHost }<br>
7.Gets the of the session id No.: ${ pageContext.session.id}<br>
</body>
</html>

Operation results:

(3) Use of param and paramvalues objects

Code example: create test.jsp in the web directory

<body>

    Get request parameters username Value of: ${ param.username } <br>

    Get request parameters password Value of: ${ param.password } <br>

    Gets the first of the request parameters hobby Value of: ${ paramvalues.hobby[0] } <br>

    Gets the second of the request parameters hobby Value of: ${ paramvalues.hobby[1] } <br>

    <%--  There are more than one with the same name key When using paramvalues The index value of determines which one to get, using param Only the first one can be obtained  --%>

    use param obtain hobby Value of: ${ param.hobby } <br>

</body>

Operation results:
Browser address bar input: http://localhost:8080/mytest/test.jsp ?username=jaychou&password=123&hobby=sing&hobby=dance

(4) Use of header and headervalues objects

Code example: create test.jsp in the web directory

<body>

    Output request header[user-agent]Value of: ${ header["user-agent"] }<br>

    First in the output request header[user-agent]Value of:${ headervalues["user-agent"][0] }<br>

</body>

(5) Use of cookie objects

Code example: create test.jsp in the web directory

<body>

    obtain cookie Name of: ${ cookie.jsessionid.name } <br>

    obtain cookie Value of: ${ cookie.jsessionid.value } <br>

</body>

Operation results:

(6) Use of initparam object

Code example: write parameters in web.xml (after modifying the content in web.xml, the service needs to be restarted to take effect)

<context-param>

    <param-name>username</param-name>

    <param-value>root</param-value>

</context-param>

<context-param>

    <param-name>url</param-name>

    <param-value>jdbc:mysql:///test</param-value>

</context-param>

Create test.jsp in the web directory

<body>

    output&lt;context-param&gt;username Value of: ${ initparam.username } <br>

    output&lt;context-param&gt;url Value of: ${ initparam.url } <br>

</body>

Operation results:

--------------------------------------------------------------END------------------------------------------------------------

The el expression determines whether the list set is empty

 

Tags: html Java Javascript

Posted by overlordofevil on Mon, 20 Sep 2021 17:31:12 +0530