The full name of EL is Expression Language (expression language), which is one of the most important features of jsp2.0. EL expressions can be used to access data in the application to eliminate java scripts in the jsp page.
Syntax of el expression
Expression For example, x+y can be written as {x+y}
Keywords in el
The following are keywords in el, which cannot be used as identifiers:
and,eq,gt,true,instanceof,or,le,false,empty,not,lt,ge,null,div,mod
1. Introduction to EL expressions
EL's full name is Expression Language. EL's main functions:
1. Obtain data
EL expressions are mainly used to replace script expressions in JSP pages to retrieve java objects and obtain data from various types of web domains. (Objects in a certain web domain, access javabean properties, access list collection, access map collection, access array)
2. Perform operations
Using EL expressions, you can perform some basic relational operations, logical operations and arithmetic operations in the JSP page to complete some simple logical operations in the JSP page. ${user==null}
3. Obtain common objects for web development
EL expressions define some implicit objects. Using these implicit objects, web developers can easily obtain references to commonly used web objects, thereby obtaining data in these objects.
4. Call Java methods
EL expressions allow users to develop custom EL functions to call methods of Java classes through EL expressions in JSP pages.
1.1. Obtain data
Use EL expression to get data syntax: "${identifier}"
When the EL expression statement is executed, the pageContext.findAttribute method will be called, using the identifier as the keyword to find the corresponding object from the four fields of page, request, session, and application. If it is found, it will return the corresponding object. If it is not found, it will return "" (note that it is not null, but an empty string).
EL expressions can easily obtain JavaBean properties, or obtain data of arrays, collections, and Map types.
Example of el expression to obtain data:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-"%><%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><%@page import="me.gacl.domain.Person"%><%@page import="me.gacl.domain.Address"%><!DOCTYPE HTML><html><head><title>el expression gets data</title></head><body><% request.setAttribute("name","Lonely Wolf");%><%--${name} is equivalent to pageContext.findAttribute("name") --%>Use EL expression to obtain data: ${name} <hr><!-- In jsp page, use el expression to obtain the properties of the bean--><% Person p = new Person();p.setAge();request.setAttribute("person",p);%>Use el expression to obtain the properties of the bean: ${person.age}<hr><!-- In jsp page, use el expression to obtain the properties of the bean. . . . . . . . . Attributes of --><% Person person = new Person();Address address = new Address();person.setAddress(address);request.setAttribute("person",person);%>${person.address.name}<hr><!-- In the jsp page, use the el expression to obtain the data at the specified position in the list collection--><% Person p = new Person();p.setName("Lonely Canglang");Person p = new Person();p.setName("White Tiger God Emperor");List<Person> list = new ArrayList<Person>();list.add(p);list.add(p);request.setAttribute("list",list);%><!-- Take the data at the specified location of the list -->${list[].name} <!-- Iterate the List collection --><c:forEach var="person" items="${list}">${person.name}</c:forEach><hr><!-- In the jsp page, use the el expression to get the data of the map collection --><% Map<String,String> map = new LinkedHashMap<String,String>();map.put("a","aaaaxxx");map.put("b","bbbb");map.put("c","cccc");map.put("","aaaa");request.setAttribute("map",map);%><!-- Get the data of the map collection based on the keyword -->${map.c} ${map[""]}<hr><!-- Iterate Map collection--><c:forEach var="me" items="${map}">${me.key}=${me.value}<br/></c:forEach><hr></body></html> The operation effect is as follows:
1.2. Execute operations
Syntax: ${operation expression}, EL expression supports the following operators:
1. Relational operators
2. Logical operators:
3. empty operator: check whether the object is null (empty)
4. Binary expression: ${user!=null?user.name :""}
5. [ ] and . operators
Example of performing operations using EL expressions:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-"%><%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><%@page import="me.gacl.domain.User"%><!DOCTYPE HTML><html><head><title>el expression operator</title></head><body><h>el expression performs four operations:</h>Addition operation: ${+}<br/>Subtraction operation: ${-}<br/>Multiple operation: ${*}<br/>Divide operation: ${/}<br/>H>el expression performs relationship operations:</h><%--${user == null} and ${user eq null}; Equivalent-%>${user == null}<br/>${user eq null}<br/>${user eq null}<br/>el expression uses the empty operator to check whether the object is null(empty)</h><% List<String> list = new ArrayList<String>();list.add("gacl");list.add("xdp");request.setAttribute("list",list);%><%--Use the empty operator to check whether the object is null(empty) --%><c:if test="${!empty(list)}"><c:forEach var="str" items="${list}">${str}<br/></c:forEach></c:if><br/>%List<String> emptyList = null;%><%--Use the empty operator to check whether the object is null(empty) --%><c:if test="${empty(emptyList)}">Sorry, there is no data you want to see</c:if><br/><h>Binary expressions are used in EL expressions</h><% session.setAttribute("user",new User("Lonely Ganglang"));%>${user==null? "Sorry, you are not logged in" : user.username}<br/><h>EL expression data echo</h><% User user = new User();user.setGender("male");//Data echo request.setAttribute("user",user);%><input type="radio" name="gender" value="male" ${user.gender=='male'?'checked':''}>Male<input type="radio" name="gender" value="female" ${user.gender=='female'?'checked':''}>Female<br/> </body></html>The operation results are as follows:
1.3. Obtain common objects for web development
EL expression language defines 11 implicit objects. Using these implicit objects can easily obtain some common objects in web development and read the data of these objects.
Syntax: ${implicit object name}: Get a reference to the object
Test 11 implicit objects in EL expressions:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-"%><!DOCTYPE HTML><html><head><title>el implicit object</title></head><body><br/>-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //map%>${pageScope.name}<br/>------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ //map%>${sessionScope.user}<br/>--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- This expression is often used on data echoes --><form action="${pageContext.request.contextPath}/servlet/RegisterServlet" method="post"><input type="text" name="username" value="${param.username}"><input type="submit" value="register"></form><br/>------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- http://localhost:/JavaWeb_EL_Study_/ELDemo.jsp?like=aaa&like=bb -->${paramValues.like[]} ${paramValues.like[]} <br/>---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- , for example Accept-Encoding, headerValues["Accept-Encoding"]--%>${header["Accept-Encoding"]}<br/>------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ A Map object that stores all http request header fields. For a request parameter, it returns a string[] array. For example: headerValues.Accept returns a string[] array. headerValues.Accept[] takes out the first value in the array--%>${headerValues.Accept[]}<br/><%--${headerValues.Accept-Encoding} When writing this way, an error will be reported when testing headerValues. If there is "-" in the header, such as Accept-Encoding, headerValues["Accept-Encoding"]headerValues["Accept-Encoding"][] returns a string[] array. headerValues["Accept-Encoding"][][] takes out the first value in the array--%>${headerValues["Accept-Encoding"][]}<br/>----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -->${cookie.JSESSIONID.value} //Save map of all cookies<br/>------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Configure initialization parameters in web.xml file --><context-param><param-name>xxx</param-name><param-value>yyyy</param-value></context-param><context-param><param-name>root</param-name><param-value>/JavaWeb_EL_Study_</param-value></context-param>--%><%--Get map in servletContext to save initialization parameters --%>${initParam.xxx}<br/>${initParam.root}</body></html> The code of RegisterServlet is as follows:
package me.gacl.web.controller;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class RegisterServlet extends HttpServlet {/* * Methods for handling user registration*/public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//, receive parameter String userName = request.getParameter("username");/*** , jump back to /ELDemo.jsp page, do not use request.setAttribute("userName", userName) to store userName in the request object* However, in the ELDemo.jsp page, you can use ${param.username} to get the value of the username parameter in the request object*/request.getRequestDispatcher("/ELDemo.jsp").forward(request, response);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}} The test results are as follows:
Notice:
When testing header and headerValues, if there is "-" in the header, such as Accept-Encoding, header["Accept-Encoding"] and headerValues["Accept-Encoding"]
When testing cookies, for example, ${cookie.key} takes a cookie object. If you access the name and value of the cookie, you must have ${cookie.key.name} or ${cookie.key.value}
1.4. Call Java methods using EL
EL expression syntax allows developers to develop custom functions to call methods of Java classes. Syntax: ${prefix: method(params)}
The only thing that can be called in the EL expression is the static method of the Java class. The static method of this Java class needs to be described in the TLD file before it can be called by the EL expression.
EL custom functions are used to extend the functions of EL expressions, allowing EL expressions to complete functions that ordinary Java program code can complete.
1.5. EL Function Development Steps
Generally speaking, the development and application of EL custom functions include the following three steps:
1. Write a static method of a Java class
2. Write a tag library descriptor (tld) file and describe custom functions in the tld file.
3. Import and use custom functions in JSP page
Example: Developing el function to escape html tags
1. Write the html escape processing tool class, and add static processing methods to escape html tags in the tool class, as follows:
package me.gacl.util;/*** @ClassName: HtmlFilter* @Description: html escape processing tool class* @author: Lonely Canglang* @date: -- Morning::**/ public class HtmlFilter {/*** @Method: filter* @Description: Static method, html tag escape processing* @Anthor: Lonely Canglang** @param message Content to escape* @return Content after escape*/ public static String filter(String message) {if (message == null)return (null);char content[] = new char[message.length()];message.getChars(, message.length(), content, );StringBuffer result = new StringBuffer(content.length + );for (int i = ; i < content.length; i++) {switch (content[i]) {case '<':result.append("<");break;case '>':result.append(">");break;case '&':result.append("&");break;case '"':result.append("");break;default:result.append(content[i]);}}return (result.toString());}}2. Write a tag library descriptor (tld) file in the WEB-INF directory and describe custom functions in the tld file.
The code of elFunction.tld is as follows:
<?xml version="." encoding="UTF-"?><taglib version="." xmlns="http://java.sun.com/xml/ns/jee"xmlns:xsi="http://www.w.org//XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/jee web-jsptaglibrary__.xsd"><tlib-version>.</tlib-version><short-name>EL Function</short-name><!-- A reference URI for a custom EL function library can be quoted like this in a JSP page: <%@taglib uri="/ELFunction" prefix="fn" %> --><uri>/ELFunction</uri><!--<function> element is used to describe an EL custom function --><function><description>html tag escape processing method</description><!--<name> child element is used to specify the name of the EL custom function --><name>filter</name><!--<function-class> child element is used to specify the complete Java class name --><function-class>me.gacl.util.HtmlFilter</function-class><!--<function-signature> child element is used to specify the signature of the static method in the Java class. The method signature must indicate the return value type of the method and the type of each parameter, and each parameter is separated by a comma. --><function-signature>java.lang.String filter(java.lang.String)</function-signature></function></taglib>
3. Import and use custom functions in JSP page
<%@ page language="java" import="java.util.*" pageEncoding="UTF-"%><%--Introducing EL custom function library--%><%@taglib uri="/ELFunction" prefix="fn" %><!DOCTYPE HTML><html><head><title>Calling Java methods using EL</title></head><body><%--Calling filter methods using EL--%>${fn:filter("<a href=''>Diand</a>")}</body></html> The operation results are as follows:
1.6. Things to note when developing EL Function
After writing the tag library description file, you need to place it in any subdirectory except classes and lib directories in the <web application>/WEB-INF directory or in the WEB-INF directory.
The <uri> element in the TLD file uses the URI that specifies the TLD file. This URI needs to be used to introduce the tag library description file in the JSP file.
The <function> element is used to describe an EL custom function, where:
The <name> child element is used to specify the name of the EL custom function.
The <function-class> child element is used to specify the complete Java class name.
The <function-signature> child element is used to specify the signature of a static method in a Java class. The method signature must indicate the return value type of the method and the type of each parameter, and each parameter is separated by a comma.
1.7. EL precautions
EL expressions are a technique in the JSP 2.0 specification. Therefore, if you want to correctly parse EL expressions, you need to use a WEB server that supports Servlet2.4/JSP2.0 technology.
Note: Some Tomcat servers cannot use EL expressions
(1) Upgrade to tomcat6
(2) Add <%@ page isELIgnored="false" %> to JSP
1.8. EL expressions retain keywords
The so-called reserved word means that when naming variables, the above names should be avoided to avoid errors during program compilation. There are so many summaries about the content of EL expressions.
The above content provides detailed introduction to the relevant knowledge of Javaweb El expressions through examples. I hope it will be helpful to you. At the same time, I would like to thank you very much for your support for Wulin.com website!