BCSP-Xuanzi Java Development Java Web Programming CH08_Using EL and JSTL to Simplify JSP Pages

BCSP-Xuanzi Java Development Java Web Programming CH08_Using EL and JSTL to Simplify JSP Pages

EL expressions

Disadvantages of Writing Java Script in JSP

  • Program structure is complex
  • poor readability
  • difficult to maintain
<td width="380">@<%= blog.getOrigin().getUser().getNickname() + ":"
            + blog.getOrigin().getContent() %></td>

Using EL expressions can greatly simplify JSP code

<td width="380">@${blog.origin.user.nickname} : ${blog.origin.content}</td>

Get to know EL expressions

What is EL expression: Expression Language (expression language)

The function of EL

  • Replace complex coding when accessing data in JSP pages
  • execute expression

Characteristics of EL

  • automatic conversion type
  • Simple to use

EL expression syntax

${<!-- -->expression}

Get variable value by variable name

<% request.setAttribute("username","Zhang Ming"); %>
Username: ${<!-- -->username}
Username: ${<!-- -->requestScope.username}

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-VhyqMeCp-1687707043347)(./assets/image-20230625153305528.png)]

If the scope is omitted, it will be searched in the order of page → request → session → application scope, and return if found, and return null if not found

EL expression corresponds to the name of the JSP scope

Property Scope Name in EL Expression Property Scope Name in EL Expression
page pageScope session sessionScope
request requestScope application applicationScope

Object elements and collection elements in EL expressions

  • Get the property value of the object through the operator
  • dot operator
${<!-- -->user.name}
  • [ ] operator
${<!-- -->user["name"]}
  • Get the value in the List collection
${<!-- --> listName[0] }
${<!-- --> listName[1] }
// List collection element subscript
  • Get the value in the Map collection
${<!-- --> map.keyName }
${<!-- --> map["keyName"] }
// Map collection element key name

Use EL expressions to output user information

Use EL expression to get user information stored in Map

<%
      Map<String,String> map = new HashMap<String,String>();
      map.put("name","Zhang Ming");
      map.put("hobby","playing badminton");
      request.setAttribute("user",map);
%>
  Username: ${<!-- -->user.name}<br/>
  User hobby: ${<!-- -->user["hobby"]}<br/>

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-eFvs4RJz-1687707043348)(./assets/image-20230625153606131.png)]

EL operator

Arithmetic operators

Arithmetic Operators Description Example Result
+ Add ${10 + 5} 15
minus ${10-5} 5
* Multiply ${10*5} 50
/ or div except ${10/5} or ${10 div 5} 2
% or mod Model ${10%5 } or ${10 mod 5} 0

If the content on both sides of the “+” operator in the EL expression cannot be automatically converted to a numeric type, the expression will throw an exception

Relational operators

Arithmetic Operators Description Example Result
== or eq equal to ${23==5} or ${23 eq 5}${" a" =="a"} or ${"a" eq "a"} falsetrue
!= or ne not equal ${23!=5} or ${23 ne 5} true
< or lt less than ${23<5} or ${23 lt 5} false
> or gt greater than ${23> 5} or ${23 gt 5} true
<= or le less than or equal to ${23<=5} or ${23 le 5} false
>= or ge greater than or equal to ${23>=5} or ${23 ge 5} true

Logical and Empty operators

Arithmetic Operators Description Example strong> result
& amp; & amp; or and Logical AND If A is true and B is false, then ${A & amp; & amp; B} or ${A and B} false
||or logical or `If A is true and B is false, then ${A
! or not logical NOT if A is true , then ${!A} or ${not A} false

Empty operator Empty operator is a prefix operator used to check whether a variable is empty

<% request.setAttribute("username","Zhang Ming"); %>
${<!-- -->empty username} // returns false
${<!-- -->not empty username} // returns true
${<!-- -->! empty username} // returns true

Implicit objects for EL expressions

Can read information directly from different scopes and requests

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-a6EfN4H0-1687707043349)(./assets/image-20230625154234766.png)]

Scope Access Object

Object name Description
pageScope Map class associated with attributes in page scope
requestScope Map class associated with attributes in request scope
sessionScope The Map class associated with the attributes in the session scope
applicationScope The Map class associated with the attributes in the application scope
  • If a scope is specified, EL expressions will look for variable values within that scope
  • If no scope is specified, the EL expression will search for variable values in the order of page → request → session → application

Parameter access object

object name description
param Access the Map object of a single request value according to the parameter name
paramValues Access the Map object of the array request value according to the parameter name

JSP implicit object

Object name Description
pageContext Provides access to page information and JSP built-in objects

The first access object

Object name Description
header The Map class that stores the main values of the request header by name
headerValues The Map class that stores all the values of the request header as a String array and returns the specified request String array of all header values
cookie Map class that stores cookies attached to the request by name

Initialization parameter access object

Object name Description
initParam Map class that stores web application context initialization parameters by name

JSTL

  • EL expression encapsulates the function of data access, but does not provide logic control function
  • The JSTL tag library encapsulates functions such as logic control, loop control, and data formatting.
  • The combination of the two can fully realize the development requirements of dynamic pages

What is JSTL

JSP Standard Tag Library (JSP Standard Tag Library)

  • Contains a set of standard tags for common functionality when developing JSP pages

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-uABeC51o-1687707043349)(./assets/image-20230625154657479.png)]

Benefits

  • JSP page logic control can be realized without embedding Java code
  • With EL expressions, it is convenient to implement JSP page coding
  • code concise

Introducing JSTL

  • Reference the jar file of JSTL in the project
    • Add the jar package in the WEB-INF/lib directory
    • Right-click to select the jar file to be imported, select the "Add as Library..." menu item, and import the jar package
  • Import the tag library using the taglib directive on the JSP page
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
  • uri: Specifies the tag library to be imported

  • prefix: Specify an alias for the imported tag library, the core tag library generally uses c

  • Use standard tag library
<c:tag name>

JSTL tag library commonly used tags

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-X7sxDm1x-1687707043349)(./assets/image-20230625154933985.png)]

Universal tag library-out tag

Used to output expression results, similar to expressions in JSP<%=%>

<c:out value="<string>" default="<string>" escapeXml="<true|false>"/>
  • value: the operation result of the output expression, which can be obtained through EL expressions
  • default: The default value output when the value of the value attribute is empty

Use the out tag for output

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
    pageContext.setAttribute("content1",null);
    pageContext.setAttribute("content2","Tencent.com");
%>

${content2}

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-xXWzMryO-1687707043350)(./assets/image-20230625155127853.png)]

General tag library-set tag

Set the value of a scoped variable or property value

<c:set var="<string>" value="<string>" scope="<string>"
            target="<string>" property="<string>" />
  • var: the variable name to set
  • value: the variable value to store
  • scope: the scope of variables, including page, request, session, application
  • target: The JavaBean object or Map object to be set. EL expressions can be used
  • property : In the case of a JavaBean object or a Map object, the object property or key to be set
  • If the target attribute is specified, the property attribute also needs to be specified

Two ways to use the set tag

  • Store the value in the variable var whose scope is scope
<c:set var="userName" scope="session" value="Jerry"/>
  • var: declare variable
  • Set scope range
  • variable assignment
  • Set the value value to the property of the object
<c:set value="1000" target="${employee}" property="salary"/>
  • target: specify the object name
  • property: specify object properties

Universal tag library-remove tag

Used to remove the specified variable in the specified scope

<c:remove var="<string>" scope="<string>"/>
  • var: the name of the variable to be removed
  • scope: the scope of the variable

Use the remove tag to remove variables

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

Current username value: username =

After removing the attribute: username =

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-6L0joSGF-1687707043350)(./assets/image-20230625155949721.png)]

Conditional tag library-if tag

Used to implement logic control, similar to the if keyword in Java

<c:if test="condition" var="varName" scope="scope">
    Main content
</c:if>
  • test: Judgment condition, when the execution result is true, execute the content in the if tag. EL expressions can be used
  • var: Define variables to store the execution results of expressions
  • scope: the scope of the variable, including page, request, session, application

Use the if tag to transform the pagination function

<p align="center">Current page count:[${pageObj.currPageNo}/${pageObj.totalPageCount}]
    <c:if test="${pageObj.currPageNo > 1}">
        <a href="../control/blog?opr=allBlogList & amp;keyword=${keyword} & amp;pageIndex=1">Homepage</a>
        <a href="../control/blog?opr=allBlogList & amp;keyword=${keyword}
                 &pageIndex=${pageObj.currPageNo - 1}">Previous page
        </a>
    </c:if>
    <c:if test="${pageObj.currPageNo < pageObj.totalPageCount}">
        <a href="../control/blog?opr=allBlogList & amp;keyword=${keyword}
                 &pageIndex=${pageObj.currPageNo + 1}">Next page
        </a>
        <a href="../control/blog?opr=allBlogList & amp;keyword=${keyword}
                 & amp;pageIndex=${pageObj.totalPageCount}">Last page
        </a>
    </c:if>
</p>

Conditional tag library-choose tag

, and tags are used to realize the logic control of mutual exclusion relationship

<c:choose var="varName" scope="scope">
    <c:when test="condition1">
        Main content
    </c:when>
     ...
    <c:otherwise>
        Main content
    </c:otherwise>
</c:choose>
  • when : execute the body content in the tag when the test expression condition is met
  • otherwise: Execute the content of the otherwise tag when all the when tags are not satisfied
  • when tags can have multiple
  • The otherwise tag must be the last tag in the choose tag

Iteration tag library-forEach tag

Loop through the collection

<c:forEach items="collectionName" var="varName" begin="beginIndex"
            varStatus="varStatusName" end="endIndex" step="step">
    Main content
</c:forEach>
  • var: the reference of the current element during the loop
  • varStatus: store information about elements referenced by var attributes, such as indexes, etc.
  • begin : the starting position of the loop
  • end : the end position of the loop
  • step : the step size of the loop, which can be omitted, and the default is 1

El combined with JSTL

Call the static method of the class through the EL expression

  • Add a file with the suffix .tld in WEB-INF
  • Import the tag library descriptor file using the taglib directive in the JSP page
<%@ taglib uri="http://mycompany.com" prefix="util" %>
  • Calling a static method of a class through an EL expression
${<!-- -->util:getFormatTime(comment.time)}
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
    // some code omitted...
    <tlib-version>1.0</tlib-version>
    <short-name>util</short-name>
    <uri>http://mycompany.com</uri>
    <function>
    <name>getFormatTime</name>
        <function-class>org.microblog.util.DateUtil</function-class>
    <function-signature>java.lang.String getFormatTime( java.util.Date )
    </function-signature>
    </function>
</taglib>
  • name: method name
  • function-class: the class where the method is located
  • function-signature: the executed method, the method name is consistent with the class

Use the forEach tag to traverse the Map

  • Introduce Map related packages in JSP
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

Create a Map and store the province information in the Map

<%
    Map<String,String> map=new HashMap<String,String>();
    map.put("Wuhan", "Hubei Province");
    map.put("Luoyang", "Henan Province");
    // some code omitted...
    request.setAttribute("map", map);
%>

Use the forEach tag to traverse the Map

<c:forEach var="entry" items="${map}">
<p>${entry.key} ${entry.value}</p>
</c:forEach>

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-9M2sqslP-1687707043350)(./assets/image-20230625163125346.png)]