EL expressions and JSTL tag library

2023.10.25

What is EL expression?

EL expression, Expression Language, can replace the java code in JSP, making the program in the JSP file look cleaner and more beautiful. Since JSP is mixed with various java codes, such as <% java code %>, <%=%>, etc., the JSP file is very confusing and difficult to maintain, so EL expressions are created. EL expressions can be regarded as part of the JSP syntax, and EL expressions belong to JSP.

ps: EL expressions generally operate on data in domain objects and cannot operate on local variables.

EL expressions preferentially read data from small ranges: pageContext < request < session < application

Usage of EL expression

The role of EL expression:

Gets data from a scope, converts it to a string, and outputs it to the browser.

1. Get data from a certain domain.

  • pageContext

  • request

  • session

  • application

2. Convert the retrieved data into a string.

  • If it is a java object, the toString method of the java object will be automatically called to convert it into a string.

3. Output the string to the browser.

  • Like this: <%= %>, to output it to the browser.

Basic syntax format of EL expression:

${expression}

Use cases of EL expressions:

<%
//Create User object
User user = new User();
user.setUsername("jackson");
user.setPassword("1234");
user.setAge(50);

// Store the User object in a certain domain. It must be saved because EL expressions can only take data from a certain range.
//Data must be stored in one of the four major ranges.
request.setAttribute("userObj", user);
%>

Use EL expression to get the User object:

${userObj}
//Equivalent to java code: <%=request.getAttribute("userObj")%>

ps: Interview question: What is the difference between ${userObj} and ${“userObj”}?

${userObj} means fetching data from a certain domain, and the name of the fetched data is “userObj”. There must be such code before: domain.setAttribute(“userObj”, object) ;
${“userObj”} means to directly output “userObj” to the browser as a normal string. Data will no longer be fetched from a domain.

How to output the attribute values of an object?

${userObj.username} The premise for using this syntax is that the User object has the getUsername() method.
${userObj.password} The premise for using this syntax is that the User object has a getPassword() method.
${userObj.age} The premise for using this syntax is that the User object has a getAge() method.
${userObj.email} The premise for using this syntax is that the User object has a getEmail() method.
The syntax . in the EL expression actually calls the underlying getXxx() method.
Note: If there is no corresponding get method, an exception will occur. Report 500 error.

EL expressions are preprocessed for null. If null, an empty string is output to the browser.

There are four implicit scopes in EL expressions:

  • pageScope corresponds to the pageContext scope.

  • requestScope corresponds to the request scope.

  • sessionScope corresponds to the session scope.

  • applicationScope corresponds to the application scope.

How to get data from the Map collection:

${map.key}

How to get data from arrays and List collections:

  • ${array[0]}

  • ${array[1]}

  • ${list[0]}

Directives to ignore EL expressions:

<%@page contentType="text/html;charset=UTF-8" isELIgnored="true" %>
isELIgnored="true" means ignoring the EL expression
isELIgnored="false" means that EL expressions are not ignored. (It's the default value)

isELIgnored="true" This is a global control.

You can use backslashes for local control: \${username} This also ignores EL expressions. 

Get the root of the application through EL expression:

  • ${pageContext.request.contextPath}

ps: EL expression does not have a built-in request object, so you cannot directly use request to obtain the root of the application. You need to use the built-in object pageContext to obtain the request first.

JSTL tag library

What is JSTL tag library?

Java Standard Tag Lib (Java standard tag library). Usually used in conjunction with EL expressions. The purpose is to make the java code in JSP disappear.

Steps to use JSTL tag library:

  1. Introduce the jar package corresponding to the JSTL tag library. Create a new lib directory under WEB-INF, and then copy the jar package to lib. ps: Here is an explanation of why some jar packages are placed under lib (such as mysql driver jar package and JSTL tag library jar package), and some jar packages are deployed in the idea settings (such as servlet-api.jar, jsp- api.jar): The jar package deployed directly in the idea is the jar package of the Tomcat server itself. It is deployed here just to associate it with the idea. The jar package placed under lib is a third-party jar package, and the Tomcat server does not come with it.
  2. When introducing tag libraries into JSP. (Use the taglib directive to import the tag library.)
  3. Just use the label wherever you need it. On the surface, tags are used, but the bottom layer is actually a Java program.

Principle of JSTL tag:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
The path behind the above uri actually points to a xxx.tld file.
The tld file is actually an xml configuration file.
The relationship between "tags" and "java classes" is described in the tld file.
The tld file corresponding to the above core tag library is: c.tld file. where is it.
There is a c.tld file in the META-INF directory in jakarta.servlet.jsp.jstl-2.0.0.jar. 

Case study of using JSTL tag library:

<%@ page import="jsp.Student" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>

<%@ page import="java.util.List" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%
    // Create List collection
    List<Student> stuList = new ArrayList<>();

    //Create Student object
    Student s1 = new Student("3", "Iverson");
    Student s2 = new Student("24", "Kobe");
    Student s3 = new Student("23", "Jordan");

    //Add to List collection
    stuList.add(s1);
    stuList.add(s2);
    stuList.add(s3);

    // Store the list collection in the request field
    request.setAttribute("stuList", stuList);
%>


//Requirement: Traverse the elements in the List collection. Output student information to the browser
//Use java code to implement
<%
    // Get the List collection from the domain
    List<Student> stus = (List<Student>)request.getAttribute("stuList");
    //Write a for loop to traverse the list collection
    for(Student stu : stus){
%>
id:<%=stu.getId()%>,name:<%=stu.getName()%><br>
<%
    }
%>



//Use jstl tag library to implement
//Use the forEach tag in the core tag library. Traverse the List collection
//EL expressions can only take data from the domain.
//The name after var is arbitrary. The var attribute represents each element in the collection.
<c:forEach items="${stuList}" var="s">
    id:${s.id},name:${s.name}<br>
</c:forEach>

The above cases demonstrate respectively using and not using the jstl tag library to traverse the elements in the collection. The results of accessing the server are as follows:

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 138,295 people are learning the system