Detailed explanation of JSP El expression

Time:2021-7-9

1、 Introduction to El expression

  • Expression language
  • It is a simple way to get data in JSP page (only get data, not set data)
  • Introducing concepts in JSP 2.0

Grammatical format

In any static part of the JSP page, you can get the value of the specified expression through ${expression}

2、 El get data (get attributes from four domains)
El can only get attributes from four domains
1. If the built-in object of El is not used, the order of finding data is to find the attribute value with the specified name from the four major fields from small to large

2、 El get data (get attributes from four domains)

El can only get attributes from four domains

1. If the built-in object of El is not used, the order of finding data is to find the attribute value with the specified name from the four major fields from small to large


- pageContext<request<session<application

  <%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8"%>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Insert title here</title>
  </head>
  <body>
   <%
    pageContext.setAttribute("name", "linjie");
    request.setAttribute("name", "lucy");
    session.setAttribute("name", "king");
    application.setAttribute("name", "bilibili");
   %>
   name=${name }
  </body>
  </html>

这里写图片描述

It can be seen that when no El built-in object is used, the search order is from small to large, so the first one to display is in the pagecontext field

2. Using the El built-in object to obtain data from the specified domain improves the efficiency of search


<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 <%
  pageContext.setAttribute("name", "linjie");
  request.setAttribute("name", "lucy");
  session.setAttribute("name", "king");
  application.setAttribute("name", "bilibili");
 %>
 name=${applicationScope.name }
</body>
</html>

这里写图片描述

It can be seen that the output of name in the application field can be specified by using applicationscope. Of course, other fields are similar. We will talk about the built-in objects related to the attributes of these four fields

3、 Built in objects in El

El has 11 built-in objects. Here we mainly talk about four domain attributes and the other four
Among the 11 built-in objects of El, except for pagecontext, the other 10 built-in objects are all Java. Util. Map

1. Domain attribute related (4)

  • Pagescope: find the specified key from the property space of page scope field
  • Request scope: finds the specified key from the request scope property space
  • Sessionscope: finds the specified key from the property space of the session scope field
  • Applicationscope: finds the specified key from the application scope attribute space

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 <%
  pageContext.setAttribute("name", "linjie");
  request.setAttribute("name", "lucy");
  session.setAttribute("name", "king");
  application.setAttribute("name", "bilibili");
 %>

 name=${applicationScope.name }<br>
 name=${pageScope.name }<br>
 name=${sessionScope.name }<br>
 name=${requestScope.name }<br>
</body>
</html>

这里写图片描述

2. Other important built-in objects (4)

1、pageContext

The pagecontext and the JSP built-in object pagecontext are the same object. Through this object, you can obtain the request, response, session, ServletContext, ServletConfig and other objects. Note: these objects are not built-in objects in El, they can only be obtained through pagecontext

In El, you can get the request object by ${pagecontext. Request}, and the underlying call is the pagecontext. Getrequest() method. Similarly, you can get other objects in a similar way

Key points: the most commonly used ones are as follows:${pageContext.request.contextPath }, representing the root under the web application, we can see that the path in the following action is more readable

Regster.java


package linjie.com;

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 Regster extends HttpServlet {
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  response.getWriter().append("Served at: ").append(request.getContextPath());
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doGet(request, response);
 }

}

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<% -- ${pagecontext. Request. Contextpath} represents the root of Web Application --% >
 <form action="${pageContext.request.contextPath }/regster" method="POST">
  xxx<input type="text" name="name"/><br>
  yyy<input type="text" name="age"/><br>
  < input type = "submit" value = "click" >
 </form>
</body>
</html>

这里写图片描述

2. Param (get the specified parameters in the request)

The underlying layer actually calls request. Getparameter ()

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<% -- ${pagecontext. Request. Contextpath} represents the root of Web Application --% >
 <form action="${pageContext.request.contextPath }/show.jsp" method="POST">
  xxx<input type="text" name="name"/><br>
  yyy<input type="text" name="age"/><br>
  < input type = "submit" value = "click" >
 </form>
</body>
</html>

show.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 name=${param.name }<br>
 age=${param.age }<br>
</body>
</html>

Customer browser access results

这里写图片描述 

这里写图片描述

3、paramValues

Get all the values of the specified parameters in the request, and the bottom layer actually calls request. Getparametervalues ()

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<% -- ${pagecontext. Request. Contextpath} represents the root of Web Application --% >
 <form action="${pageContext.request.contextPath }/show.jsp" method="POST">
  xxx<input type="text" name="name"/><br>
  yyy<input type="text" name="age"/><br>

  Hobbies:
  < input type = "checkbox" name = "hobby" value = "sleep" > sleep
  < input type = "checkbox" name = "hobby" value = "play" > play
  < input type = "checkbox" name = "hobby" value = "eat" > eat
  < input type = "submit" value = "click" >
 </form>
</body>
</html>

show.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 name=${param.name }<br>
 age=${param.age }<br>


 hobby[0]=${paramValues.hobby[0] }<br>
 hobby[1]=${paramValues.hobby[1] }<br>
</body>
</html>

Customer browser display results

这里写图片描述

这里写图片描述

4、initParam

Get the initialization parameter. The underlying call is ServletContext. Getinitparameter ()

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
 <display-name>07eltttt</display-name>
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>

<!-- Initialization parameter -- >
 <context-param>
 <param-name>name</param-name>
 < param value > Lin Jie
 </context-param>


 <servlet>
 <display-name>Regster</display-name>
 <servlet-name>Regster</servlet-name>
 <servlet-class>linjie.com.Regster</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>Regster</servlet-name>
 <url-pattern>/regster</url-pattern>
 </servlet-mapping>
</web-app>

index.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 name=${initParam.name }
</body>
</html>

Customer browser display results

这里写图片描述

4、 El accessing bean properties

1. What is java bean

JavaBeans are public Java classes, but they are used for editing tool recognition

At least three conditions need to be met

  • There is a public default constructor (such as a parameterless constructor)
  • Attributes are accessed by public get and set methods, that is, set to private. At the same time, the size of get and set methods and attribute names also need to correspond. For example, the attribute name and get method should be written as public string getname () {}, n uppercase.
  • Serialization is required. This is the framework, the tool must reflect the state of cross platform

2. Accessing bean properties

El can get the specified value through ${key. Attribute}, and its underlying layer actually calls the get method of the corresponding attribute of the object

Demo.java


package linjie.com;
/*
 *Bean 
 */
public class Demo {
 private String name;
 private int age;
 public Demo(String name,int age){
  this.name=name;
  this.age=age;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 @Override
 public String toString() {
  return super.toString();
 }

}

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
 import="linjie.com.Demo"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 <%
  Demo test=new Demo("linjie",12);
  request.setAttribute("ELttt", test);
 %>
 name=${requestScope.ELttt.name }<br>
 age=${requestScope.ELttt.age }<br>

 <!--  If you access the property of a null object, El will not throw a null pointer exception, but will not display it -- >
 names=${requestScope.ELtttxx.name }<br>

</body>
</html>

Customer browser display results

这里写图片描述

5、 El access data in array

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>  
<body>
 <%
  String[] names={"xlj","lucy","king"};
  pageContext.setAttribute("names", names);
 %>
 name[1]=${names[1] }<br>

 <!--  If the subscript of the accessed array element exceeds the upper limit of the array subscript, El will not throw an out of bounds exception, but will not display -- >
 names[5]=${names[5] }<br>
</body>
</html>

Here is an array of access classes

Stu.java


package linjie.com;
/*
 *Bean 
 */
public class Stu {
 private String sname;
 private String address;
 public Stu() {
  super();
 }

 public Stu(String sname, String address) {
  super();
  this.sname = sname;
  this.address = address;
 }

 public String getSname() {
  return sname;
 }

 public void setSname(String sname) {
  this.sname = sname;
 }

 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }

 @Override
 public String toString() {
  return super.toString();
 }


}

index.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
 import="linjie.com.*"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

 <%
  Stu[] stus=new Stu[3];
  stus[0]=new Stu("xlj","A");
  stus[1]=new Stu("lucy","B");
  stus[2]=new Stu("kingA","C");
  pageContext.setAttribute("stus",stus);
 %>
 stus[1].Sname=${stus[1].sname }
</body>
</html>

Customer browser display results

这里写图片描述

6、 Get the data in the list

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 <%
  List<String> names=new ArrayList<String>();
  names.add("xlj");
  names.add("lucy");
  pageContext.setAttribute("names", names);
 %>

 <!--  Because the bottom layer of list is an array, it can be written as follows -- >
 names[1]=${names[1] }<br>
</body>
</html>

Customer browser display results

这里写图片描述

be careful:

El can access list through index, but cannot access set. Because there is no index concept in set

7、 El access map


<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 <%
  Map<String,Object> map=new HashMap<String,Object>();
  map.put("age", 20);
  map.put("name", "xlj");
  pageContext.setAttribute("map", map);
 %>
 name=${map.name }<br>
 age=${map.age }<br>
</body>
</html>

Customer browser display results

这里写图片描述

8、 Operator (empty) in El

1. Let’s talk about some common operators

  • Arithmetic operators: +, -, *, /,%, (+ +, -) are not supported
  • Relational operators: = =,! =, >, > =, <<=
  • Logical operators:!, & &, |, | not、and、or
  • Conditional operator:?:
  • Value operator: [], point

2. Empty operator

The usage is ${empty variable}, and the result is Boolean

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 <%
  String name1=null;
  String name2="";
  List<String> name3=new ArrayList<String>();

  pageContext.setAttribute("name1", name1);
  pageContext.setAttribute("name2", name2);
  pageContext.setAttribute("name3", name3);
 %>
 Empty for undefined variables, the operation result is true:
 empty namex=${empty namex }<br>

 Empty for null reference, the result is true:
 empty name1=${empty name1 }<br>

 Empty for a string reference that is an empty string, the operation result is true:
 empty name2=${empty name2 }<br>

 Empty for arrays or collections without elements, the result is true:
 empty name3=${empty name3 }<br>
</body>
</html>

Customer browser display results

这里写图片描述

9、 Custom El function

Because El itself does not have the ability to handle strings, you can customize El functions
-Define function (New myel. Java class)
-Registration: first find jsp2-example-taglib.tld, and copy the header and registration function to the. TLD file you created (. TLD is placed under WEB-INF)
-To use it in index.jsp, you need <% @ taglib URI = ” http://tomcat.apache.org/jsp2-example-taglib ” prefix=”MyEL” %>

1. Define the function myel.java

package linjie.com;


//Custom function
//This class and its functions need to be registered in the XML file with the extension. TLD
//TLD: tag library definition
//XML files need to be constrained, that is, the configuration file header. This head constraint can be copied from the following file
//In the Tomcat installation directory: webapps, examples, WEB-INF, jsp2
//The file is: jsp2-example-taglib.tld

//The. TLD XML file needs to be defined in the WEB-INF directory of the current web project, and the XML file ending with. TLD should be created in this directory
//Copy the header in jsp2-example-taglib.tld to the created XML file

//Then register the function, or copy it in the bottom of JSP 2-example-taglib.tld
public class MyEL {
 private static MyEL instance;
 public static MyEL getInstance() {
  if(instance==null)
  {
   instance=new MyEL();
  }
  return instance;
 }

 //String lowercase to uppercase
 public static String LowerToUpper(String str) {
  return str.toUpperCase();
 }
}

2. Copy the header part and the registration function part at the bottom of jsp2-example-taglib.tld to the TLD (under WEB-INF) file you created

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

MyEL.tld

<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
 version="2.0">

 <!--  Define tag library information -- >
 <description>A tag library exercising SimpleTag handlers.</description>
 <tlib-version>1.0</tlib-version>
 <short-name>MyEL</short-name><!--  The label library name is generally defined as the same as the file name -- >
 <uri>http://tomcat.apache.org/jsp2-example-taglib</uri>

 <!--  Register function -- >
  <function>
  <name>MyLowerToUpper</name>
  <function-class>linjie.com.MyEL</function-class><!--  Method class -- >
  <function-signature>java.lang.String LowerToUpper( java.lang.String )</function-signature><!--  Method signature: return value, method name and parameter are required
 </function>
</taglib>

3. To use it in index.jsp, you need <% @ taglib URI = ” http://tomcat.apache.org/jsp2-example-taglib ” prefix=”MyEL” %>

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<%@ taglib uri=" http://tomcat.apache.org/jsp2-example-taglib " prefix="MyEL" %><!--  Uri and short name in TLD -- >
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 <!--  This method name is the name of TLD registration -- >
 ${MyEL:MyLowerToUpper("sasas") }<br>


 <!--  El functions can only handle attribute values and string constants in the four fields -- >
 <%
  String name="xlj";
  pageContext.setAttribute("name", name);
 %>
 ${MyEL:MyLowerToUpper(name) }<br>

</body>
</html>

Customer browser display results

这里写图片描述

10、 El summary

  • El expressions cannot appear in Java code blocks, expression blocks and other JSP dynamic code parts
  • El can only get data from the four domain attribute spaces (pagecontext, request, session, application)
  • El doesn’t throw null pointer exception, it just doesn’t show it
  • El does not throw an array out of bounds exception, but does not display it
  • El does not have the ability to process strings (JSTL El or user-defined El functions can be used)

This article about the detailed explanation of JSP El expression is introduced here. For more related JSP El expression content, please search previous articles of developer or continue to browse the following related articles. I hope you can support developer more in the future!

Recommended Today

Hot! Front and rear learning routes of GitHub target 144K

Hello, Sifu’s little friend. I’m silent Wang Er. Last week, while appreciating teacher Ruan Yifeng’s science and technology weekly, I found a powerful learning route, which has been marked with 144K on GitHub. It’s very popular. It covers not only the front-end and back-end learning routes, but also the operation and maintenance learning routes. As […]