跳至主要內容

表达式与JSTL

wangdx大约 16 分钟

项目地址open in new window

表达式语言简介

Servlet 与 JSP 处理结构

在项目开发中,用户的请求可以直接发送给 JSP 或 Servlet 来进行处理,相比较 JSP 程序来讲,使用 Servlet 可以更加方便的编写程序代码,所以常见的开发形式就是请求提交到 Servet 中而后将 Servlet 处理好的数据(假设此数据通过数据库获取)利用 request 属性交由 JSP 进行打印输出

@WebServlet("/ELServlet") //一般在定义Servlet路径的时候还是愿意使用原始的类名称
public class ELServlet extends HttpServlet {// 设计缺陷:这种强制性的继承操作一定是不可取的
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("message", "沐言科技:www.yootk.com"); // request属性
        req.getRequestDispatcher("/show.jsp").forward(req, resp); // 服务端跳转
    }
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@include file="/pages/plugins/include_basepath.jsp" %>
<html>
<head>
  <base href="<%=basePath%>">
</head>
<body>
<h1>【传统型】直接输出mesasge属性:<%=request.getAttribute("message")%></h1>
<%
  if (request.getAttribute("message") != null) {	// 当前存在有message属性
%>
<h1>【改进型】判断后输出message属性:<%=request.getAttribute("message")%></h1>
<%
  }
%>
<h1>【EL处理】${message}</h1>
</body>
</html>

表达式基础语法

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@include file="/pages/plugins/include_basepath.jsp" %>
<html>
<head>
  <base href="<%=basePath%>">
</head>
<body>
<h1>【param标志位】message参数内容 = ${param.message}</h1>
<h1>【header标志位】请求主机:${header.host}</h1>
<h1>【header标志位】链接来源:${header.Referer}</h1>
<h1>【cookie标志位】SESSIONID:${cookie.JSESSIONID.value}</h1>
<h1>【pageContext标志位】上下文路径:${pageContext.request.contextPath}</h1>
<h1>【pageContext标志位】当前访问路径:${pageContext.request.requestURL}</h1>
<h1>【pageContext标志位】用户请求模式:${pageContext.request.method}</h1>
<h1>【pageContext标志位】SESSIONID:${pageContext.session.id}</h1>
</body>
</html>

EL 与四种属性范围

表达式语言属性输出

判断使用表达式语言最重要的一项功能是进行属性信息的获取,尤其是在 Servlet 跳转到 JSP 页面显示时,更是需要实现对 request 属性的处理,在 JSP 中最简单的属性获取方式为“${属性名称}”,而这种方式最大的特点是会通过属性范围的保存顺序由小到大开始查找

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@include file="/pages/plugins/include_basepath.jsp" %>
<html>
<head>
  <base href="<%=basePath%>">
</head>
<body>
<%	// 实现四种属性内容的设置,同时保证属性的名称相同
  pageContext.setAttribute("message1", "【Page属性】www.yootk.com");
  request.setAttribute("message1", "【Request属性】www.yootk.com");
  session.setAttribute("message1", "【Session属性1】www.yootk.com");
  application.setAttribute("message", "【Application属性】www.yootk.com");
%>
<h1>${message}</h1>

<%	// 实现四种属性内容的设置,同时保证属性的名称相同
  pageContext.setAttribute("message", "【Page属性】www.yootk.com");
  request.setAttribute("message", "【Request属性】www.yootk.com");
  session.setAttribute("message", "【Session属性】www.yootk.com");
  application.setAttribute("message", "【Application属性】www.yootk.com");
%>
<h1>获取Page属性内容:${pageScope.message}</h1>
<h1>获取Request属性内容:${requestScope.message}</h1>
<h1>获取Session属性内容:${sessionScope.message}</h1>
<h1>获取Application属性内容:${applicationScope.message}</h1>
</body>
</html>

EL 与简单 Java 类

通过 EL 输出对象信息

简单 Java 类是 Java 项目开发中最为重要的组成结构,在实际项目中每一个单 Java 类对象都可以保存一组详细的信息,同时利用引用关联的结构还可以实现关联对象信息的存储,但是最终存储的数据一定要通过 request 属性交由 JSP 进行输出,而在 JSP 中就可以利用 EL 语法支持,实现对象中全部属性的输出

简单 Java 类

这样在简单 Java 类中往往都会针对于属性提供有相应的 getter 方法,就可以利用 EL 的语法基于反射机制实现对象中属性信息的输出,现在假设有两个简单 Java 类:雇员信息(Emp)以及部门信息(Dept)同时每一个雇员都包含有一个部门信息的引用

【雇员信息】雇员编号:${emp.empno}<br>
【雇员信息】雇员姓名:${emp.ename}<br>
【部门信息】部门编号:${emp.dept.deptno}<br>
【部门信息】部门名称:${emp.dept.dname}<br>
【部门信息】部门位置:${emp.dept.loc}<br>

EL 与 List 集合

传递 List 集合

项目开发中除了需要进行单个对象的转发外,也有可能需要通过 Servlet 收集一组数据(List 集合),这样在将属性传递到 JSP 页面时就需要通过迭代的形式进行信息的输出

通过 EL 迭代 List 集合

在 Java 类集框架中,如果要想输出 List 集合的内容,那么就一定要通过迭代的形式完成,传统的迭代操作中由于存在有泛型的支持,可以直接获取到具体的对象类型,从而实现对象属性的获取,但是如果此时要结合 EL 输出时,往往都不会导入对应的程序包,那么这时就可以通过 pageContext 属性来进行每次迭代结果的保存,随后再利用 EL 语法支持获取每一个对象的属性内容

@WebServlet("/ELServlet") // 一般在定义Servlet路径的时候还是愿意使用原始的类名称
public class ELServlet extends HttpServlet { // 设计缺陷:这种强制性的继承操作一定是不可取的

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Dept> depts = new ArrayList<>(); // 定义要保存的数据集合
        for (int x = 0 ; x < 10 ; x ++) {    // 根据你自己的情况选择是否要循环多次
            Dept dept = new Dept(); // 实例化要保存的VO对象
            dept.setDeptno(10000L + x); // 随意生成一个部门编号
            dept.setDname("沐言科技教学部 - " + x); // 设置部门名称
            dept.setLoc("北京");
            depts.add(dept); // 将对象保存在集合之中
        }
        req.setAttribute("allDepts", depts); // request属性
        req.getRequestDispatcher("/show.jsp").forward(req, resp); // 服务端跳转
    }
}
<table border="1">
  <thead>
  <tr>
    <td>部门编号</td>
    <td>部门名称</td>
    <td>部门位置</td>
  </tr>
  </thead>
  <tbody>
  <tr>
    <td>${allDepts[0].deptno}</td>
    <td>${allDepts[0].dname}</td>
    <td>${allDepts[0].loc}</td>
  </tr>
  <tr>
    <td>${allDepts[1].deptno}</td>
    <td>${allDepts[2].dname}</td>
    <td>${allDepts[3].loc}</td>
  </tr>
  </tbody>
</table>

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>	<%-- 只要遇见了List集合输出,直接找到Iterator/foreach --%>
<html>
<head>
</head>
<body>
<%	// 进行属性的接收,但是此时没有使用到泛型,因为要使用泛型就必须导入VO包
	List all = (List) request.getAttribute("allDepts"); // 直接接收List
	Iterator iterator = all.iterator(); // Iterator也无法使用泛型
%>
<table border="1">
	<thead>
		<tr>
			<td>部门编号</td>
			<td>部门名称</td>
			<td>部门位置</td>
		</tr>
	</thead>
	<tbody>
	<%
		while (iterator.hasNext()) {
			// iterator.next()返回的是Object类型,而setAttribute()可以设置的属性内容也是Object
			pageContext.setAttribute("dept", iterator.next()); // page属性范围的特点在于本页面保存
	%>
		<tr>
			<td>${dept.deptno}</td>
			<td>${dept.dname}</td>
			<td>${dept.loc}</td>
		</tr>
	<%
		}
	%>
	</tbody>
</table>
</body>
</html>

EL 与 Map 集合

1、
package com.yootk.servlet;

import com.yootk.vo.Dept;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/ELServlet") // 一般在定义Servlet路径的时候还是愿意使用原始的类名称
public class ELServlet extends HttpServlet { // 设计缺陷:这种强制性的继承操作一定是不可取的

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, Dept> depts = new HashMap<>(); // 定义要保存的数据集合
        for (int x = 0 ; x < 10 ; x ++) {    // 根据你自己的情况选择是否要循环多次
            Dept dept = new Dept(); // 实例化要保存的VO对象
            dept.setDeptno(10000L + x); // 随意生成一个部门编号
            dept.setDname("沐言科技教学部 - " + x); // 设置部门名称
            dept.setLoc("北京");
            depts.put("yootk-"+x, dept); // 将对象保存在集合之中
        }
        req.setAttribute("allDepts", depts); // request属性
        req.getRequestDispatcher("/show.jsp").forward(req, resp); // 服务端跳转
    }
}


2、
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>	<%-- 只要遇见了List集合输出,直接找到Iterator/foreach --%>
<html>
<head>
</head>
<body>
<%	// 进行属性的接收,但是此时没有使用到泛型,因为要使用泛型就必须导入VO包
	Map all = (Map) request.getAttribute("allDepts"); // 直接接收List
	Iterator iterator = all.entrySet().iterator(); // Iterator也无法使用泛型
%>
<table border="1">
	<thead>
		<tr>
			<td>KEY</td>
			<td>部门编号</td>
			<td>部门名称</td>
			<td>部门位置</td>
		</tr>
	</thead>
	<tbody>
	<%
		while (iterator.hasNext()) {
			// iterator.next()返回的是Object类型,而setAttribute()可以设置的属性内容也是Object
			pageContext.setAttribute("entry", iterator.next()); // page属性范围的特点在于本页面保存
	%>
		<tr>
			<td>${entry.key}</td>
			<td>${entry.value.deptno}</td>
			<td>${entry.value.dname}</td>
			<td>${entry.value.loc}</td>
		</tr>
	<%
		}
	%>
	</tbody>
</table>
</body>
</html>

3、
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>
<table border="1">
	<thead>
		<tr>
			<td>部门编号</td>
			<td>部门名称</td>
			<td>部门位置</td>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>${allDepts["yootk-0"].deptno}</td>
			<td>${allDepts["yootk-0"].dname}</td>
			<td>${allDepts["yootk-0"].loc}</td>
		</tr>
	</tbody>
</table>
</body>
</html>

4、
package com.yootk.servlet;

import com.yootk.vo.Dept;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/ELServlet") // 一般在定义Servlet路径的时候还是愿意使用原始的类名称
public class ELServlet extends HttpServlet { // 设计缺陷:这种强制性的继承操作一定是不可取的

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<Integer, Dept> depts = new HashMap<>(); // 定义要保存的数据集合
        for (int x = 0 ; x < 10 ; x ++) {    // 根据你自己的情况选择是否要循环多次
            Dept dept = new Dept(); // 实例化要保存的VO对象
            dept.setDeptno(10000L + x); // 随意生成一个部门编号
            dept.setDname("沐言科技教学部 - " + x); // 设置部门名称
            dept.setLoc("北京");
            depts.put(x, dept); // 将对象保存在集合之中
        }
        req.setAttribute("allDepts", depts); // request属性
        req.getRequestDispatcher("/show.jsp").forward(req, resp); // 服务端跳转
    }
}

5、
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>
<table border="1">
	<thead>
		<tr>
			<td>部门编号</td>
			<td>部门名称</td>
			<td>部门位置</td>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>${allDepts[3].deptno}</td>
			<td>${allDepts[3].dname}</td>
			<td>${allDepts[3].loc}</td>
		</tr>
	</tbody>
</table>
</body>
</html>

6、
package com.yootk.servlet;

import com.yootk.vo.Dept;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/ELServlet") // 一般在定义Servlet路径的时候还是愿意使用原始的类名称
public class ELServlet extends HttpServlet { // 设计缺陷:这种强制性的继承操作一定是不可取的

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<Long, Dept> depts = new HashMap<>(); // 定义要保存的数据集合
        for (int x = 0 ; x < 10 ; x ++) {    // 根据你自己的情况选择是否要循环多次
            Dept dept = new Dept(); // 实例化要保存的VO对象
            dept.setDeptno(10000L + x); // 随意生成一个部门编号
            dept.setDname("沐言科技教学部 - " + x); // 设置部门名称
            dept.setLoc("北京");
            depts.put((long) x, dept); // 将对象保存在集合之中
        }
        req.setAttribute("allDepts", depts); // request属性
        req.getRequestDispatcher("/show.jsp").forward(req, resp); // 服务端跳转
    }
}

EL 运算符

1、

<h1>数字加法运算:${param.num + 100}</h1>
<h1>数字乘法运算:${param.num * 100}</h1>

2、
http://localhost/show.jsp?num=30

3、
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>
<h1>数字大小判断:${param.num1 > 100}</h1>
<h1>数字大小判断:${param.num2 lt 100}</h1>
<h1>字符串相等判断:${param.message == 'www.yootk.com'}</h1>
<h1>字符串大小判断:${param.title gt 'Yootk'}</h1>
<h1>布尔判断:${param.flag eq true}</h1>
</body>
</html>

4、
http://localhost/show.jsp?num1=30&num2=88&message=www.yootk.com&title=yootk&flag=true

5、
<h1>逻辑与:${param.num > 30 && param.url == "www.yootk.com"}</h1>
<h1>逻辑或:${param.title == "yootk" or param.title eq "YOOTK"}</h1>

6、
localhost/show.jsp?num=30&url=www.yootk.com&title=yootk

7、
<h1>空运算:${empty param.message}</h1>
<h1>三目运算:${param.age >= 18 ? "成年人" : "未成年人"}</h1>

8、
http://localhost/show.jsp?age=16&message=

JSTL

JSTL 简介

JSTL

使用 JSP 标签编程可以极大的简化 JSP 页面的代码编写,使得所有的动态程序代码都可以像 HTML 标签一样进行定义,这样就极大的改善了 JSP 中的代码编写风格。现代的 JavaWEB 可以在 JSP 中使用 JSTL (JavaServerPages Standard Tag Library.JSP 标准标识库)系统标签进行代码编写。

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%-- c表示的标签的前缀,而后在这个标签里面对应有很多的功能,使用“c:xx”的形式进行调用 --%>
<%-- uri实际上是一个tld文件,它所描述的是标签中所有可以使用到的功能定义 --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
</head>
<body>
<%	// 本次是为了简化程序的结构所以直接使用了page属性范围定义了一个属性内容,而实际的开发中肯定要通过request属性范围跳转
	pageContext.setAttribute("message", "沐言科技:www.yootk.com"); // 页面属性
%>
<h1>【EL输出】${message}</h1>
<h1>【JSTL输出】<c:out value="${message}"/></h1>
<h1>【JSTL输出】<c:out value="李兴华高薪就业编程训练营:edu.yootk.com"/></h1>
</body>
</html>

if 判断标签

if 判断

在 JSP 页面中进行数据显示时,往往需要做根据不同的数据进行分支逻辑的处理,所以在 JSTL 核心标签库中提供了 if 判断指令,此指令可以直接根据 EL 的逻辑判断结果来决定最终的执行状态,该标签语法如下:

1、
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%-- c表示的标签的前缀,而后在这个标签里面对应有很多的功能,使用“c:xx”的形式进行调用 --%>
<%-- uri实际上是一个tld文件,它所描述的是标签中所有可以使用到的功能定义 --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
</head>
<body>
<%
	if (true) {
%>
		<h1>显示一些自己所需要的信息内容!</h1>
<%
	}
%>
</body>
</html>

2、
package com.yootk.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/ELServlet") // 一般在定义Servlet路径的时候还是愿意使用原始的类名称
public class ELServlet extends HttpServlet { // 设计缺陷:这种强制性的继承操作一定是不可取的

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, Object> map = new HashMap<>(); // 定义Map集合
        map.put("flag", true); // 设置属性内容
        map.put("age", 18); // 设置属性内容
        map.put("muyan", "yootk.com"); // 设置属性内容
        req.setAttribute("result", map); // 将所需要的内容保存在request属性范围之中
        req.getRequestDispatcher("/show.jsp").forward(req, resp); // 服务端跳转
    }
}


3、
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head><title>沐言科技:www.yootk.com</title></head>
<body>
<c:if test="${result.flag}">
    <c:if test="${result.age <= 18}">
        <h2>恭喜你,年轻人,未来是你的!</h2>
        <c:if test="${result.muyan == 'yootk.com'}">
            <h2>沐言科技:www.yootk.com</h2>
        </c:if>
    </c:if>
</c:if>
<c:if test="${result.flag == false}">
    <h2>这里没有你想看的结果,拜拜了您呐!</h2>
</c:if>
</body>
</html>

forEach 迭代标签

1、

<c:forEach items="" var="" begin="" end="" step="" varStatus="">
    定义循环体程序代码
</c:forEach>

2、
package com.yootk.servlet;

import com.yootk.vo.Dept;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/ELServlet") // 一般在定义Servlet路径的时候还是愿意使用原始的类名称
public class ELServlet extends HttpServlet { // 设计缺陷:这种强制性的继承操作一定是不可取的

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Dept> depts = new ArrayList<>();
        for (int x = 0; x < 3; x++) {
            Dept dept = new Dept();
            dept.setDeptno(1900L + x);
            dept.setDname("沐言科技教学部 - " + x);
            dept.setLoc("北京");
            depts.add(dept);
        }
        req.setAttribute("allDepts", depts); // 保存集合属性
        req.getRequestDispatcher("/show.jsp").forward(req, resp); // 服务端跳转
    }
}

3、
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head><title>沐言科技:www.yootk.com</title></head>
<body>
<c:if test="${allDepts != null}">   <%-- 这个判断是否加入与最终的结果无关 --%>
    <table border="1">
        <thead>
            <tr>
                <td>部门编号</td>
                <td>部门名称</td>
                <td>部门位置</td>
            </tr>
        </thead>
        <tbody>
            <c:forEach items="${allDepts}" var="dept">
                <tr>
                    <td>${dept.deptno}</td>
                    <td>${dept.dname}</td>
                    <td>${dept.loc}</td>
                </tr>
            </c:forEach>
        </tbody>
    </table>
</c:if>
</body>
</html>

4、
package com.yootk.servlet;

import com.yootk.vo.Dept;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/ELServlet") // 一般在定义Servlet路径的时候还是愿意使用原始的类名称
public class ELServlet extends HttpServlet { // 设计缺陷:这种强制性的继承操作一定是不可取的

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, Dept> depts = new HashMap<>();
        for (int x = 0; x < 3; x++) {
            Dept dept = new Dept();
            dept.setDeptno(1900L + x);
            dept.setDname("沐言科技教学部 - " + x);
            dept.setLoc("北京");
            depts.put("muyan-" + x, dept);
        }
        req.setAttribute("allDepts", depts); // 保存集合属性
        req.getRequestDispatcher("/show.jsp").forward(req, resp); // 服务端跳转
    }
}

5、
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head><title>沐言科技:www.yootk.com</title></head>
<body>
<c:if test="${allDepts != null}">   <%-- 这个判断是否加入与最终的结果无关 --%>
    <table border="1">
        <thead>
            <tr>
                <td>KEY</td>
                <td>部门编号</td>
                <td>部门名称</td>
                <td>部门位置</td>
            </tr>
        </thead>
        <tbody>
            <c:forEach items="${allDepts}" var="entry">
                <tr>
                    <td>${entry.key}</td>
                    <td>${entry.value.deptno}</td>
                    <td>${entry.value.dname}</td>
                    <td>${entry.value.loc}</td>
                </tr>
            </c:forEach>
        </tbody>
    </table>
</c:if>
</body>
</html>


函数标签

1、
package com.yootk.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@WebServlet("/ELServlet") // 一般在定义Servlet路径的时候还是愿意使用原始的类名称
public class ELServlet extends HttpServlet { // 设计缺陷:这种强制性的继承操作一定是不可取的

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 登录认证授权管理的时候,会将一些权限的信息保存在Set集合里面。
        Set<String> roleSet = new HashSet<>(); // 获取Set接口实例
        roleSet.add("admin");
        roleSet.add("guest");
        req.setAttribute("resultSet", roleSet); // 保存集合属性
        Map<String, String> map = new HashMap<>(); // 获取Map接口实例
        map.put("msg", "##Yootk"); // 保存数据
        map.put("ip", "192.168.1.252");
        map.put("html", "<h1><span>yootk.com</span></h1>");
        req.setAttribute("resultMap", map);
        req.getRequestDispatcher("/show.jsp").forward(req, resp); // 服务端跳转
    }
}


2、
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head><title>沐言科技:www.yootk.com</title></head>
<body>
<c:if test="${fn:contains(resultSet, 'admin')}">
    您拥有“Admin”角色信息;<br>
</c:if>
字符串拆分:<c:forEach items="${fn:split(resultMap.ip, '.')}" var="item">${item}、</c:forEach><br>
转大写字母:${fn:toUpperCase(resultMap.msg)}<br>
<c:if test="${fn:startsWith(resultMap.msg, '##')}">
    字符串以“##”开头<br>
</c:if>
数据转义:${fn:escapeXml(resultMap.html)}
</body>
</html>

格式化标签

1、
package com.yootk.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Date;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

@WebServlet("/ELServlet") // 一般在定义Servlet路径的时候还是愿意使用原始的类名称
public class ELServlet extends HttpServlet { // 设计缺陷:这种强制性的继承操作一定是不可取的
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final ZoneId ZONE_ID = ZoneId.systemDefault();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String str = "1998-02-17 19:09:15"; // 随意定义一个日期
        LocalDateTime localDateTime = LocalDateTime.parse(str, FORMATTER);
        Instant instant = localDateTime.atZone(ZONE_ID).toInstant();
        Date birthday = Date.from(instant); // 字符串转为日期型
        req.setAttribute("birthday", birthday);
        req.setAttribute("salary", 2838383);
        req.getRequestDispatcher("/show.jsp").forward(req, resp); // 服务端跳转
    }
}


2、
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head><title>沐言科技:www.yootk.com</title></head>
<body>
<h1>生日:<fmt:formatDate value="${birthday}" pattern="yyyy年MM月dd日"/></h1>
<h1>生日:<fmt:formatDate value="${birthday}" pattern="yyyy年MM月dd日 hh时mm分ss秒"/></h1>
<h1>工资:<fmt:formatNumber value="${salary}" currencyCode="zh"/></h1>
</body>
</html>

demo


上次编辑于: