EL and JSTL

EL toolkit introduction

A jar package developed by Java technology

Role: Reduce the intensity of Java command development during JSP file development

The Tomcat server itself comes with the EL toolkit ( Tomcat installation address/lib/el-api.jar )

JSP related knowledge There is a related introduction to the JSP specification in this article

EL expression

 1. Command format: ${scope object alias. Shared data}
 2. Command function:
       1) EL expression is a special command format provided by the EL toolkit [Expression command format]
       2) EL expression on the JSP file Use
       3) When executing, read the content of the specified [shared data] from the specified [scope object] and automatically write it to the response body

EL expression scope object alias

1. Scope objects that can be used by JSP files

    1) ServletContext application: global scope object

    2) HttpSession session: Session scope object

    3) HttpServletRequest request: request scope object

    4) PageContext pageContext: current page scope object

    This is a scope object unique to JSP files . Does not exist in servlet

    The shared data stored in the scope object of the current page can only be used in the current JSP file, and cannot be shared with other servlets or other JSP files

Real development process, mainly used for data sharing between JSTL tags and JSP files

    JSTL------->pageContext---->JSP

2. EL expression provides scope object alias

          JSP EL expression

      application ${applicationScope. Shared data name}

      session ${sessionScope. Shared data name}

      request ${requestScope. Shared data name}

      pageContext ${pageScope. Shared data name}

The following code demonstrates the use of java code and EL expressions to implement shared data reading in JSP

Servlet

public class OneServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //分别将共享数据添加到作用域对象
        //全局作用域对象
        ServletContext application=request.getServletContext();
        //会话作用域对象
        HttpSession session=request.getSession();

        application.setAttribute("sId",10);
        session.setAttribute("sName","mike");
        request.setAttribute("home","北京");
        //通过请求转发的方式调用index_1.jsp,由index_1.jsp负责将作用域对象共享数据读取并写入响应体中
        request.getRequestDispatcher("/index_1.jsp").forward(request,response);
    }
}

Use Java code to read shared data

<%
    //读取全局作用域对象中的共享数据
    Integer sId=(Integer) application.getAttribute("sId");
    //读取会话作用域对象中的共享数据
    String sName=(String)session.getAttribute("sName");
    //读取请求作用域对象中的共享数据
    String home=(String)request.getAttribute("home");
%>
sId:<%=sId%><br/>
sName:<%=sName%><br/>
home:<%=home%><br/>

Use EL expressions

学员Id:${applicationScope.sId}<br/>
学员姓名:${sessionScope.sName}<br/>
学员地址:${requestScope.home}<br/>

Obviously EL expression simplifies the steps of reading shared data in JSP files

EL expression writes the attribute of the referenced object into the response body

1. Command format: ${scope object alias. shared data name. attribute name}
2. Command function: read the attribute value of the reference object associated with the specified shared data from the scope object. And automatically write the result of the attribute to the response body
3. Attribute name: must refer to the type attribute name is exactly the same (case)
4. EL expression does not provide a method to traverse the collection, so the collection content cannot be read from the scope object Output

First create a Student class

public class Student {
    private Integer sId;
    private String sName;

    public Student() {
    }

    public Student(Integer sId, String sName) {
        this.sId = sId;
        this.sName = sName;
    }

    public Integer getsId() {
        return sId;
    }

    public void setsId(Integer sId) {
        this.sId = sId;
    }

    public String getsName() {
        return sName;
    }

    public void setsName(String sName) {
        this.sName = sName;
    }
}

Create Servlet

public class OneServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建一个引用类型实例对象
        Student student=new Student(10,"mike");
        //将引用类型对象存入请求作用域对象
        request.setAttribute("student",student);
        //请求转发,向Tomcat申请调用index_1.jsp
        request.getRequestDispatcher("/index_1.jsp").forward(request,response);
    }
}

index_1.jsp

学生编号:${requestScope.student.sId}<br/>
学生姓名:${requestScope.student.sName}<br/>

EL expression simplified version

1. Command format: ${shared data name}

2. Command function: EL expression allows developers to omit scope object aliases during development

3. Working principle:

   Since the simplified version of EL expression does not specify the scope of the object, it uses the [guess] algorithm during execution

  First go to [pageContext] to locate the shared data, if it exists, read the output directly and end the execution

  If the positioning is not successful in [pageContext], go to [request] to locate the shared data, if it exists, read the output directly and end the execution

  If the positioning is not successful in [request], go to [session] to locate the shared data, if it exists, read the output directly and end the execution

  If the positioning is not successful in [session], go to [application] to locate the shared data, if it exists, read the output directly and end the execution

  If the positioning is not successful in [application], return null

  pageContext--->request--->session--->application

4. There are hidden dangers:

             It is easy to reduce the program execution speed [To the contrary]

             Easily lead to data positioning errors

5. Application scenarios:

              The design purpose is to simplify the difficulty of reading and outputting shared data from pageContext

               The initial design of the simplified version is to read and output data from the current page scope object. Therefore, you should avoid using the simplified version when reading and outputting data from request, session, and application.

6. Although there are many hidden dangers in the simplified version of EL expressions, in the actual development process, in order to save time, developers generally use

  Simplified version, refuse to use the standard version

Servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //向当前用户session添加一个共享数据
        HttpSession session=request.getSession();
        session.setAttribute("key","hehe");

        //向当前请求作用域对象中添加一个共享数据
        request.setAttribute("key","haha");

        //通过请求转发方式,申请调用index_1.jsp
        request.getRequestDispatcher("/index_1.jsp").forward(request,response);
    }
}

index_1.jsp

标准版EL表达式输出session中的key值:${sessionScope.key}<br/>
简化版EL表达式输出session中的key值:${key}

EL expression supports arithmetic expressions

1. Prerequisite: Sometimes it is necessary to read the shared data for some calculations in the JSP file, and then write the calculation results to the response body

2. Operation expression:

   1) Mathematical operations

   2) Relational operations:> >= == <<= != gt ge eq lt le !=

   3) Logic operation: && ||!

Demonstrate mathematical operations

public class OneServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("key1","100");
        request.setAttribute("key2",200);
        //通过请求转发的方式调用index_1.jsp 并将结果写入到响应体中
        request.getRequestDispatcher("index_1.jsp").forward(request,response);
    }
}
<!--将作用域对象中共享数据读取出来相加,将相加的结果写入到响应体中-->
<%
    String num1=(String)request.getAttribute("key1");
    Integer num2=(Integer)request.getAttribute("key2");
    int sum=Integer.valueOf(num1)+num2;
%>
传统的java命令计算后的结果:<%=sum%>
<hr/>
EL表达式计算后的结果:${requestScope.key1+requestScope.key2}

Demonstrate relational operations

public class TwoServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("age",25);
        request.getRequestDispatcher("index_2.jsp").forward(request,response);
    }
}
<!--传统Java命令实现关系运算的输出-->
<%
    Integer age=(Integer)request.getAttribute("age");
%>
<%
    if (age>18){
%>
欢迎光临<br/>
<%
    }else {
%>
谢绝入内<br/>
<%
    }
%>
EL表达式输出关系运算
${age>18?"欢迎光临":"谢绝入内"}

Built-in objects provided by EL expressions

the term

                  definition

               param

Map the request parameter name to a single string parameter value (obtained by calling ServletRequest.getParameter (String name)). The getParameter (String) method returns a parameter with a specific name. The expression ${param. name} is equivalent to request.getParameter (name).

              paramValues

Map the request parameter name to a numeric array (obtained by calling ServletRequest.getParameter (String name)). It is very similar to the param implicit object, but it retrieves an array of strings instead of a single value. The expression ${paramvalues. name} is equivalent to request.getParamterValues(name).

             header

Map the request header name to a single string header value (obtained by calling ServletRequest.getHeader(String name)). The expression ${header. name} is equivalent to request.getHeader(name).

            headerValues

Map the request header name to a numeric array (obtained by calling ServletRequest.getHeaders(String)). It is very similar to the head implicit object. The expression ${headerValues. name} is equivalent to request.getHeaderValues(name).

           cookie

Map the cookie name to a single cookie object. The client request to the server can obtain one or more cookies. The expression ${cookie. name .value} returns the first cookie value with a specific name. If the request contains multiple cookies with the same name, the ${headerValues. name} expression should be used

           initParam

Map the context initialization parameter name to a single value (obtained by calling ServletContext.getInitparameter(String name)).

param

Equivalent to request.getParameter() in java code;

1. Command format: ${param. request parameter name}

2. Command function: Read the request parameter content in the current request packet through the request object, and write the request parameter content to the response body

3. Alternative command: index.jsp

    Send request: Http://localhost:8080/myWeb/index_1.jsp?userName=mike&password=123

        <%

        String userName =   request.getParameter("userName");

        String password =   request.getParameter("password");

      %>

     <%=userName%>

     <%=password%>

paramValues

Equivalent to request.getParameterValues() in java code;

1. Command format: ${paramValues. Request parameter name [subscript]}

2. Command function:

    If the request parameter sent by the browser is [a request parameter is associated with multiple values]

    At this time, you can read the value of the specified position under the request parameter through paramValues ​​and write it to the response body

3.代替命令: http://localhost:8080/myWeb/index_2.jsp?pageNo=1&pageNo=2&pageNo=3

    At this time, the pageNo request parameter exists in the form of an array in the request packet

    pageNo:[1,2,3]

    <%

        String  array[]= request.getParameterValues("pageNo");

    %>

    The first value: <%=array[0]%>

    The second value: <%=array[1]%>

pageContext

Corresponding complete java class name: javax.servlet.jsp.PageContext

The implicit object corresponding to this built-in object in the EL expression is: PageContext

Use the built-in object pageScope in the EL expression when fetching data from the pageContext scope using the EL expression

If you want to call the method of the pageContext built-in object, you need to use the built-in object pageContext of EL expression

Example: Use EL expression to get base path

使用java代码获取base路径
<%
    String path=request.getScheme()+"://"+request.getServerName()+request.getServerPort()+"/"+request.getContextPath();
%>
<%=path%>
<br/>
使用EL表达式内置对象PageContext
${pageContext.request.scheme}://${pageContext.request.serverName}${pageContext.request.serverPort}/${pageContext.request.contextPath}
<br/>

Use EL expressions to read data from the Map collection

<%
        Map<String,Emp> empMap=new HashMap<>();
        empMap.put("e1",e1);
        empMap.put("e2",e2);
        request.setAttribute("empMap",empMap);
 %>
    员工1:${empMap.get("e1").ename}
    员工1编号:${empMap.get("e1").eno}
    员工2:${empMap.get("e1").ename}
    员工2编号:${empMap.get("e1").eno}

Use EL expressions to read data from the List collection

<%
    List<Emp> empList=new ArrayList<Emp>();
    empList.add(e1);
    empList.add(e2);
    request.setAttribute("empList",empList);
%>
${empList[0]}
${empList[1]}
${empList[0].ename}
${empList[1].ename}

Exclusive exception of EL expression

javax.el.PropertyNotFoundException : The type [xxxx] does not exist [property name] and the corresponding property is not found in a certain class

JSTL

(JSP Standard Tag Libary) JSP standard tag library (master the core tag c tag)

Use tags instead of java code. The standard is developed by Sun and implemented by Apache (included by Sun)

Steps to use JSTL:

        *Import the jar package jstl.jar standard.jar

        *Use the taglib instruction to introduce the tag library on the jsp page that needs to use the tag amount

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

        *You can use the label directly where you need to use the label

Explain the label

<tag>
   <description></description>                                                         标签的描述
   <name>if</name>                                                                     标签的名字
   <tag-class>org.apache.taglibs.standard.tag.rt.core.IfTag</tag-class>                标签对应的需要执行的类
   <body-content>JSP</body-content>                                                    标签体中的内容类型
   <attribute>                                                                         标签中可以出现的属性
       <description></description>                                                     对属性的描述
       <name>test</name>                                                               属性的名字
       <required>true</required>                                                       该属性是否是必须的 true是必须的
       <rtexprvalue>true</rtexprvalue>                                                 该属性是否可以接收EL表达式  true表示支持接收EL表达式
	<type>boolean</type>                                                                该属性的数据类型
   </attribute>
   <attribute>
       <description></description>
       <name>var</name>
       <required>false</required>
       <rtexprvalue>false</rtexprvalue>
   </attribute>
   <attribute>
       <description></description>
       <name>scope</name>
       <required>false</required>
       <rtexprvalue>false</rtexprvalue>
   </attribute>
 </tag>

Frequently used labels

<%--模拟if...else--%>
<c:choose>
    <c:when test="${param.age<5}">
        婴幼儿
    </c:when>
    <c:when test="${param.age<18}">
        少年
    </c:when>
    <c:when test="${param.age<35}">
        青年
    </c:when>
    <c:otherwise>
        老年
    </c:otherwise>
</c:choose>
<hr/>
<%--循环foreach--%>
<c:forEach begin="1" end="10" step="1" var="i">
    ${i}
</c:forEach>
<br/>
<%--java代码--%>
<%
    for(int i=1;i<=10;i++){
    pageContext.setAttribute("i",i);
%>
${i}
<%
}
%>
<hr/>
<%--循环获取List集合--%>
<%
    List<Emp> empList=new ArrayList<Emp>();
    Emp e1=new Emp(110,"张三");
    Emp e2=new Emp(111,"李四");
    Emp e3=new Emp(112,"王五");
    empList.add(e1);
    empList.add(e2);
    empList.add(e3);
    pageContext.setAttribute("empList",empList);
%>
<c:forEach items="${empList}" var="emp" varStatus="empStatus">
    ${empStatus.count}、${emp.eno}、${emp.ename}<br/>
</c:forEach>
<br/>
<%--使用java代码--%>
<%
    for(Emp e:empList){
        pageContext.setAttribute("e",empList);
%>
<%=e.getEno()%>、<%=e.getEname()%><br/>
<%
    }
%>
<hr/>
<%--可以切割字符串--%>
<%--127.0.0.1,192.168.1.100,192.168.1.3,192.168.8.4--%>
<c:forTokens items="${initParam.ips}" delims="," var="ip">
    ${ip}<br/>
</c:forTokens>

function

1. Function is a supplement to EL expression, function is part of JSTL, corresponding configuration file is: fn.tld file in stander.jar

2. The function is also a joint EL expression and replaces the Java code in jsp

3. Function points: built-in functions, custom functions

4. Steps to use built-in functions

    *Import jar package (jstl.jar, standard.jar)

    *Use taglab instruction to import function library

    *Use it where you need to use the function

5. Detailed function

<function>                                                                                          函数描述
    <description></description>                                                                     函数名
    <name>contains</name>                                                                           函数对应的类
    <function-class>org.apache.taglibs.standard.functions.Functions</function-class>                函数对应的类中需要执行的方法
    <function-signature>boolean contains(java.lang.String, java.lang.String)</function-signature>
    <example>
      &lt;c:if test="${fn:contains(name, searchString)}">                                           例子
    </example>
  </function>

6. How to use EL label, how to use function

7. Steps to customize the label

    *Create a new egov.tld file in the WEB-INF directory and copy the template from the fn.tld file

    * Write a class, write a method in the class, the method must be public, and must be static

    *Just use

Guess you like

Origin blog.csdn.net/qq_45796208/article/details/108851273