JavaWeb speed pass EL and JSTL

Table of contents

1. EL expression

        1.Quick Start: 

            1.1 Basic introduction

            1.2 Getting Started Case

        2. Commonly used output forms: 

            2.1 Create JavaBean class

            2.2 Create JSP file

        3.empty operator: 

            3.1 Introduction

            3.2 Examples

        4.EL object: 

            4.1 EL11 built-in objects

            4.2 Domain object demonstration

            4.3 Get HTTP information

2. JSTL tag library

        1.Basic introduction: 

        2.Core core library commonly used tags: 

            2.1

            2.2

            2.3 

            2.4 /c:forEach>


1. EL expression

        1.Quick Start: 

            1.1 Basic introduction

         The full name of EL expression: Expression Language , which is the expression language
        The main function of EL expression is to replace the expression script of the JSP page <% =request.getAttribute("...") %>

         Basic syntax of EL expression: ${key} , which is more concise in form than traditional JSP expression script.

            1.2 Getting Started Case

                Taking intro.jsp as an example, the code is as follows: 

<%--
    User : Cyan_RA9
    Version : 21.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>EL expression</title>
</head>
<body>
    <%
        request.setAttribute("color", "pink");
    %>
    <%--
        PS : 若attribute为null,取出数据时,JSP方式返回"null",而EL表达式返回"".
     --%>
    <h1>传统JSP取出数据———</h1>
    color : <%= request.getAttribute("color") %> <br/>
    author : <%= request.getAttribute("author") %> <br><hr> <%--可使用三元运算符优化--%>

    <h1>采用EL表达式取出数据———</h1>
    color : ${color} <br/>
    author : ${author}
</body>
</html>

                operation result: 

        2. Commonly used output forms: 

            2.1 Create JavaBean class

                The Movie class code is as follows: 

package el;

import java.util.List;
import java.util.Map;

/**
 * @author : Cyan_RA9
 * @version : 21.0
 * @what : 标准JavaBean类
 */
public class Movie {
    private String name;
    private int length;
    private List<String> platforms;
    private Map<String, String> comments;

    public Movie() {
    }

    public Movie(String name, int length, List<String> platforms, Map<String, String> comments) {
        this.name = name;
        this.length = length;
        this.platforms = platforms;
        this.comments = comments;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public List<String> getPlatforms() {
        return platforms;
    }

    public void setPlatforms(List<String> platforms) {
        this.platforms = platforms;
    }

    public Map<String, String> getComments() {
        return comments;
    }

    public void setComments(Map<String, String> comments) {
        this.comments = comments;
    }

    @Override
    public String toString() {
        return "Movie{" +
                "name='" + name + '\'' +
                ", length=" + length +
                ", platforms=" + platforms +
                ", comments=" + comments +
                '}';
    }
}

            2.2 Create JSP file

                The output.jsp file code is as follows: 

<%@ page import="el.Movie" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.HashMap" %><%--
    User : Cyan_RA9
    Version : 21.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>EL output</title>
</head>
<body>
    <h1>输出Movie对象的信息</h1>
    <%
        Movie movie = new Movie();
        movie.setName("Matrix");
        movie.setLength(150);

        ArrayList<String> platforms = new ArrayList<>();
        platforms.add("Bilibili");
        platforms.add("YouTube");
        platforms.add("Youku");
        movie.setPlatforms(platforms);

        HashMap<String, String> comments = new HashMap<>();
        comments.put("Cyan", "It's a so nice film!");
        comments.put("Rain", "I like it!");
        comments.put("Ice", "Pretty good!");
        movie.setComments(comments);

        //将movie对象放入request域对象中
        request.setAttribute("movie", movie);
    %>
    <%-- 取出数据 --%>
    Movie.name = ${movie.name} <br/>
    Movie.length = ${movie.length} <br/>

    Movie.platforms = ${movie.platforms} <br/>
    Movie.platforms[2] = ${movie.platforms[2]} <br/>
    Movie.platforms[2] = ${movie.platforms.get(2)} <br/>

    Movie.comments = ${movie.comments} <br/>
    Movie.comments_Cyan = ${movie.comments.get("Cyan")} <br/>
    Movie.comments_Rain = ${movie.comments["Rain"]} <br/>
</body>
</html>

                operation result: 

        3.empty operator: 

            3.1 Introduction

         The empty operation can determine whether a data is empty. If it is empty, it returns true, otherwise it returns false.

        2° It is empty in the following situations——
          
● value = null
          ● value = ""
          ● value = new Object[] {} (Object array with length 0)
          ● List collection with 0 elements
          ● Map collection with 0 elements

            3.2 Examples

                empty.jsp code is as follows: 

<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.HashMap" %><%--
    User : Cyan_RA9
    Version : 21.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>empty expression</title>
</head>
<body>
    <%
        request.setAttribute("key1", null);
        request.setAttribute("key2", "");
        request.setAttribute("key3", new Object[]{});
        request.setAttribute("key4", new ArrayList<>());
        request.setAttribute("key5", new HashMap<>());
    %>
    <%-- 判断是否为空 --%>
    key1是否为空: ${empty key1} <br/>
    key2是否为空: ${empty key2} <br/>
    key3是否为空: ${empty key3} <br/>
    key4是否为空: ${empty key4} <br/>
    key5是否为空: ${empty key5}
</body>
</html>

                operation result: 

        4.EL object: 

            4.1 EL11 built-in objects

                As shown in the following table: 

variable type illustrate
pageContext PageContextImpl Get the nine built-in objects in JSP
pageScope Map<String, Object> Get data in pageContext domain
requestScope Map<String, Object> Get the data in the request field
sessionScope Map<String, Object> Get data in Session field
applicationScope Map<String, Object> Get the object in the ServletContext domain
param Map<String, String> Get the value of the request parameter
paramValues Map<String, String[]> Get multiple values
header Map<String, String> Get request header information
headerValues Map<String, String[]> Get multiple information from request headers
cookie Map<String, Cookie> Get the cookie information of the current request
initParam Map<String, String> Get the <context-param> context parameter configured in web.xml

            4.2 Domain object demonstration

                The elScope.jsp code is as follows: 

<%--
    User : Cyan_RA9
    Version : 21.0
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>EL scope</title>
</head>
<body>
    <%
        pageContext.setAttribute("color", "cyan");
        request.setAttribute("color", "pink");
        session.setAttribute("color", "cornflower_blue");
        application.setAttribute("color", "lightyellow");
    %>
    pageContext域_color = ${pageScope.color} <br/>
    request域_color = ${requestScope.color} <br/>
    session域_color = ${sessionScope.color} <br/>
    ServletContext域_color = ${applicationScope.color}
</body>
</html>

                operation result: 

            4.3 Get HTTP information

                The http.jsp code is as follows: 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>pageContext demo</title>
</head>
<body>
<h1>pageContext对象获取HTTP信息</h1>
<hr/>
<%  //简化形式(将request域对象放入pageContext域中)——— JSP
    pageContext.setAttribute("req", request);
%>
协议: ${ pageContext.request.scheme }<br>
协议: ${ req.scheme }<br>
服务器 ip:${ req.serverName }<br>
服务器端口:${ req.serverPort }<br>
工程路径:${ req.contextPath }<br>
请求方法:${ req.method }<br>
客户端 ip 地址:${ req.remoteHost }<br>
会话 id :${ pageContext.session.id }<br>
</body>
</html>

                operation result: 


2. JSTL tag library

        1.Basic introduction: 

        JSTL tag library refers to JSP Standard Tag Library, that is, JSP standard tag library.

        EL expression is to replace the expression script <%=%> in JSP, and JSTL is to replace the code script <%%> in JSP .
        JSTL consists of five tag libraries——
Functional scope URI prefix
core tag library http://java.sun.com/jsp/jstl/core c
format http://java.sun.com/jsp/jstl/fmt fmt
function http://java.sun.com/jsp/jstl/functions fn
Database ( not used ) http://java.sun.com/jsp/jstl/sql sql
XML ( not used ) http://java.sun.com/jsp/jstl/xml x

        To use JSTL, you need to import jar packages (impl and spec). PS: Tomcat10 version has changes in its dependence on jar packages (jakarta) . After importing the jar package, you need to restart Tomcat . The URL to download the jar package is as follows: 

Apache Taglibs - Apache Standard Taglib: JSP[tm] Standard Tag Library (JSTL) implementations

         taglib introduces tags, which should be placed at the beginning of the line .

        2.Core core library commonly used tags: 

            2.1 <c:set></c:set>

        (1) The <c:set></c:set> tag can save data to the domain, which is equivalent to - domain object.setAttribute (key, value);

        (2)   Which domain is the scope attribute set saved to?
                page represents the PageContext domain (default value)
                request represents the Request field
                session display Session area
                application display ServletContext area
        (3) The var attribute is used to set the key (key)
        (4) The value attribute is used to set value (value)

            2.2 <c:if></c:if>

        (1) The <c:if></c:if> tag is used to make if judgments.
        (2) The test attribute indicates the conditions for judgment (output using EL expression)

            2.3 <c:choose> <c:when> <c:otherwise>

        (1) The usage format is as follows——

< c :choose >
        < c :when test =" ${ requestScope .score   >=  90  } " >
                <h1>Awesome~</h1>
        </ c :when >
        < c :when test =" ${ requestScope . score  >= 80   } " >
                <h1>Not bad~</h1>
        </ c :when >
        < c :otherwise >
                <h1>Fly! </h1>
        </ c :otherwise >
</ c :choose >
        (2) If you use EL expression to retrieve data without specifying a domain range, the default is to search from small to large.

            2.4 <c : forEach>/c:forEach>

        (1) The <c:forEach></c:forEach> tag is used to traverse the output. There are mainly four traversal forms:
                ● Ordinary traversal outputs i to j (front closed and back closed)
                ● Traverse the array
                ● Traverse Map
                ● Traverse List
        (2) Related attributes——
                1> Ordinary traversal:
                        The index at which begin attribute setting starts
                        The end attribute sets the end index
                        The step attribute represents the step value of the traversal.
                        The var attribute represents the variable of the loop (also the data currently being traversed).
                2> Traverse the array: 

                        The data traversed by the collection
                        var traversed by items (similar to enhanced for; the domain will be automatically locked when outputting )

                        eg : 
                        <%
                                request.setAttribute("books", new String[]{"Harry Potter", "Lord of the Rings"});
                        %>
                        <c:forEach items ="${requestScope.books}" var ="book">
                                bookName = ${book} <br/>
                        </c:forEach>
                3> Traverse the Map collection:
                        eg : 
                        <%
                                Map<String, String> students = new HashMap<>();
                                map.put("Cyan", "425");
                                map.put("Rain", "400");
                                map.put("Ice", "430");
                                request.setAttribute("students", students);
                        %>
                        <c:forEach items="${requestScope.students}" var="student">
                                Student's Info = ${student.key} --- ${student.value} <br/>
                        </c:forEach>
                4> Traversing the List collection: 
                        ΔTraversing the List collection is similar to the steps when traversing the Map collection, both like the enhanced for loop structure in Java.
                        The varStatus attribute represents the status of the currently traversed data. You can get attribute values ​​such as step, begin, and end.
                        PS: The corresponding JavaBean class needs to provide the corresponding getXxx method .

        System.out.println("END----------------------------------------------------------------------------------------------------------------------");

Guess you like

Origin blog.csdn.net/TYRA9/article/details/132262121