EL (expression language) and JSTL(JSP Standard Tag Library)
Java code can be used to realize page display logic in JSP pages, but HTML and Java code are mixed in web pages, which brings difficulties to the design and maintenance of web pages. Users can apply EL to access and process data in applications, or use JSTL to replace the Java code displaying logic in web pages, so that JSP pages can minimize the use of Java code, Convenient for future maintenance.
Expression language (EL) is new in JSP 2.0. The syntax is as follows: ${expression}
EL expression is similar to JSP expression <% = expression% >. The expression in EL will be directly sent to the browser for display. Whether EL expression is supported is indicated by the isELIgnored attribute of the page instruction. When isELIgnored is true, JSP cannot use EL expression, and isELIgnored is true by defau lt.
The syntax of EL is simple. EL uses "[]" and ". Operators to access data. It mainly uses EL to obtain the attributes of objects, including obtaining the attribute value of JavaBean, obtaining the elements in the array and obtaining the elements of collection objects. Null values are directly displayed as empty strings instead of null, and null pointer exceptions will not occur during operation, Therefore, using EL to access the properties of an object does not need to judge whether the object is a null object.
EL expression has five arithmetic operators, namely addition, subtraction, multiplication, division and remainder.
There are 6 relational operators, which are equal to, not equal to, greater than, greater than or equal to, less than, less than or equal to. 3 logical operators, logical and &, logical or |, logical not! There is also A conditional operator, such as ${A?B:C}. If A is true, the result of B is calculated and returned. If A is false, the result of C is calculated and returned. There is also A null judgment operator, ${empty A}. If A does not exist, it returns true.
There are 11 EL implied objects in total. We only learn a few commonly used ones, namely pageScope, requestScope, sessionScope, applicationScope, param and paramvalue. The EL implied objects related to the scope of action include pageScope, requestScope, sessionScope and applicationScope, which can obtain the data in pagecontext, request, session and application of JSP implied objects respectively, If the scope is not specified by an implicit object in EL, it will be searched from page, request, session and application in turn. If it is found, it will be returned directly. If it is not found, it will return an empty string.
The format of data obtained is as follows:
${EL implied object. Keyword object. Property}
or
${EL implied object. Keyword object}
The objects related to the request parameters are param and paramValues. The format of obtaining data is as follows:
${EL implied object. Parameter name}
Let's take a look at a small case, write a controller, use the request object and Model object to store data in the controller class processing method, then forward it from the processing method to the show.jsp page, and display the data of the request object in show.jsp.
Model class:
public class UserBean { private String name ; private int age ; public UserBean(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; } }
Controller class:
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import pojo.UserBean; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; @Controller public class InputController { @RequestMapping("/input") public String input(HttpServletRequest request, Model model){ String [] name = {"chapter", "king", "Lee", "Lee"} ; request.setAttribute("name", name); String [] address = {"Beijing", "Shanghai", "Nanjing", "Nanchang"} ; model.addAttribute("address", address) ; ArrayList<UserBean> users = new ArrayList<>() ; UserBean b1 = new UserBean("king", 23) ; UserBean b2 = new UserBean("Hu", 22) ; UserBean b3 = new UserBean("Liu", 21) ; users.add(b1) ; users.add(b2) ; users.add(b3) ; request.setAttribute("users", users); return "show" ; } }
jsp display page:
<%-- Created by IntelliJ IDEA. User: nuist__NJUPT Date: 2021/10/1 Time: 17:04 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> from Controller Sent it request The data of built-in objects are as follows:<br> ${requestScope.name[0]}<br> ${requestScope.name[1]}<br> ${requestScope.name[2]}<br> ${requestScope.name[3]}<br> ${requestScope.users[0].name} ${requestScope.users[0].age} <br> ${requestScope.users[1].name} ${requestScope.users[1].age} <br> ${requestScope.users[2].name} ${requestScope.users[2].age} <br> from Controller Forwarded it Model The data of the object is as follows:<br> ${address[0]}<br> ${address[1]}<br> ${address[2]}<br> ${address[3]}<br> </body> </html>
JSTL tag library is composed of five different tag libraries, including Core, I18N, XML, SQL and Functions. We only learn a few commonly used tags in JSLT's Core and Functions tag libraries.
JSTL is already an integral part of Java EE 5. If you adopt an integrated development environment that supports Java EE 5 or above, you no longer need to configure JSTL.
The steps to configure JSTL are as follows:
1 - import the standard implementation of JSTL in the WEB-INF/lib directory.
2 - use taglib tag to define prefix and uri reference
General label Library of core label Library
The 1 - < C: out > tag is used to display data content in the following format:
< C: out value = "output content" >
defaultValue
</c:out>
The value value can be an EL expression or a string. default is optional. When the value value does not exist, defaultValue is output
2 - < C: set > tag can be used to set scope variables or JavaBean properties.
3 - < C: ewmove > tag. If you want to delete a variable, you can use this tag.
Process control tag of core tag library
The < C: if > tag implements the function of if statement. The specific syntax format is as follows:
< C: if test = "conditional expression" >
Subject content
</c:if>
The conditional expression can be an EL expression or a JSP expression. If the expression is true, the main content will be executed; otherwise, the main content will not be executed.
2-<c:choose> <c:when> <c:otherwise>
It is equivalent to switch, case and default. It is the same as if else statement
The specific syntax format is as follows:
<c:choose>
< C: when test = "conditional expression 1" >
Main content 1
</c:when>
< C: when test = "conditional expression 2" >
Main content 2
</c:when>
<c:otherwise>
Body whose expressions do not execute correctly
</c:otherwise>
</c:choose>
Iterative tags of core tag library
1 - < C: foreach > tag can realize the for loop in the program. The syntax format is as follows:
< C: foreach var = "variable name" items = "array or Collection object" >
Circulatory body
</c:forEach>
The items attribute can be an array or Collection object. Each time you loop, you read an element in the object and assign it to the variable specified by the var attribute. Then you can use the variable specified by var to obtain the element of the object in the loop body.
For example, there are the following codes in Contrller:
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import pojo.UserBean; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; @Controller public class ItemsController { @RequestMapping("/save") public String save(HttpServletRequest request, Model model) { ArrayList<UserBean> users = new ArrayList<>(); UserBean b1 = new UserBean("Zhang", 23); UserBean b2 = new UserBean("Liu", 22); users.add(b1) ; users.add(b2) ; request.setAttribute("users", users); return "result" ; } }
Then you can use the < C: foreach > statement to traverse the array elements in the corresponding JSP page.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%-- Created by IntelliJ IDEA. User: nuist__NJUPT Date: 2021/10/1 Time: 19:41 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <table> <tr> <th>full name</th> <th>Age</th> </tr> <c:forEach var = "user" items = "${requestScope.users}"> <tr> <td>${user.name}</td> <td>${user.age}</td> </tr> </c:forEach> </table> </body> </html>
In some cases, you need to specify the begin, end, step and varStatus attributes for the tag. Begin is the start position of the iteration, which is 0 by default. End represents the end position of the iteration, which is the last element by default. Step is the iteration step size, which is 1 by default. varStatus represents the status of iteration variables, including count, index, first and last
The < C: fortokens > tag is used to iterate over members separated by delimiters in a string.
The following code:
<c:forTokens items="Wang Guodong 1: Wang Guodong 2: Wang Guodong 3" delims=": " var = "name"> ${name}<br> </c:forTokens>
Use: split the name and assign it to var, and then use EL expression to get the value of name in turn.
Function tag library
When you call functions in JSTL in JSP pages, you need to use EL expressions. The syntax format of the call is as follows:
${fn: function name (parameter 1, parameter 2...)}
1-contains function
This function is used to judge whether a string contains the specified string. If so, it returns true; otherwise, it returns false. The definition is as follows:
contains(string,substring)
The calling example code of this function is as follows:
${fn:contains("I am studying", "am")}
2-containsIgnoreCase function
Similar to contains, it is case insensitive.
3-endsWith function
The function determines whether a string ends with a specified suffix.
It is defined as follows:
endsWith(string, suffix)
The function call instance code:
${fn:endsWith("I Am Studing", "am")}
4-indexOf function
This function returns the index of the specified string for the first time in a string. If it cannot be found, it will return - 1
5-join function
The function combines all elements in a String array into one String and separates them with the specified separator. It is defined as follows:
join(array, separator)
Function call code:
${fn:join(my, ",")}
6-length function
The function returns the number of collection elements or the number of characters in the string. Its definition is as follows:
length(input)
Function call code example:
${fn:length("wangGuodong")}
7-replace function
This function replaces all beforestring s appearing in the string with afterstring and returns the replaced result. Its definition is as follows:
replace(string, beforestring, afterstring)
8-split function
The function divides a string into an array of strings with the specified separator. It is defined as follows:
split(string, separator)
The calling examples of this function are as follows:
<c:set var = "my" value = "${fn:split('I am studying', ' ')}"/> <c:forEach var = "element" items = "${my}"> ${element}<br> </c:forEach>
Divide I am studying into spaces and pass it to my, use the forEach loop to get the value in my, and use the EL expression to get it.
9-startsWith function
This function determines whether a string starts with a specified prefix, which is defined as follows:
startWith(string,prefix)
10 substring function
The function returns a substring of a string, which is defined as follows:
substring(string, begin, end)
11 tolower case function
The function converts a string to its lowercase version.
12 touppercase function
The function converts a string to its size version
13 trim function
The function removes spaces at the beginning and end of a string
This time, I mainly studied EL expression language, JSTL core tag library and JSTL function tag library. The application of EL and JSTL greatly improves the programming efficiency and reduces the difficulty.