JSTL
-
JSTL(JSP Standard Tag Library) JSP标准标签库
-
为什么要使用JSTL?
- 使用EL可以简化JSP页面访问数据的编码,但是功能不够完善,如果要进行遍历集合操作,EL表达式无法完成,就需要借助JSTL来完成集合的遍历,实际开发中,EL表达式和JSTL结合起来使用,JSTL负责处理逻辑,EL负责展示。
-
如何使用
- 先导入jar包(一般放在WEB-INF 下的 lib 文件中)
- 在JSP页面导入标签库
- 在JSP页面中使用JSTL
-
JSTL的优点:
- 提供了一组标准标签。
- 可用于编写各种动态功能。
-
JSTL常用标签库:
- 核心标签库:
- 通用标签:set、out、remove、catch
- 条件标签:if、choose、when、otherwise
- 迭代标签:forEach
-
通用标签:set out remove catch
-
set:向域对象中添加数据
<c:set var="message" value="hello" scope="request"></c:set> ${message} // 默认是将数据保存到page作用域中,pageContext中。 // 相当于pageContext.setAttribute("key",value)。
- scope = “page” 默认,表示将数据保存到page作用域,pageContext对象中。
- scope = “reqeust”, 表示将数据保存到request作用域,request对象中。
- scope = “session”,表示将数据保存到session作用域,session对象中。
- scope = “application”,表示将数据保存到application作用域,application对象中。
<c:set target="${user}" property="name" value="张三" ></c:set>
-
out:输出域对象中的数据,于EL表达式功能类似
<c:out value="${mess}" default="未定义"></c:out> //为什么要这么写,直接用EL表达式直接输出不是更好吗? // EL表达式只能直接输出,而out可以在EL没有取出结果时,显示default的内容。
-
remove: 删除域对象中的数据
<c:remove var="mess"></c:remove>
-
catch:捕获异常
<c:catch var="error"> <% nt[] array = {1,2,3}; int num = array[3]; %> </c:catch> ${error}
-
-
条件标签: if, choose, when, otherwise
<c:set var="num1" value="1" scope="request"></c:set> <c:set var="num2" value="2" scope="request"></c:set> <c:if test="${num1 > num2}">${num1}</c:if> <c:if test="${num1 < num2}">${num2}</c:if>
<c:choose> <c:when test="${num1 > num2}">${num1}</c:when> <c:when test="${num1 < num2}">${num2}</c:when> </c:choose> 类似于Java中switch-case的写法/多个if条件
<c:choose> <c:when test="${num1 > num2}">${num1}</c:when> <c:otherwise>${num2}</c:otherwise> </c:choose> 类似于Java中的if-else
-
迭代标签:forEach
<table border="1"> <tr> <th>用户编号</th> <th>用户姓名</th> </tr> <c:forEach items="${list}" var="user"> <tr> <td>${user.id}</td> <td>${user.name}</td> </tr> </c:forEach> </table>
实例
- items:指定遍历的目标集合,从域对象中取,一般是从request中取。
- var:每次遍历出来的对象存入pageContext时的key值,循环体内部可以用EL表达式${var}进行取值。
- step:每次遍历的跨度。
- begin:遍历的起始位置。
- end:遍历的结束位置。
可以放在实例中测试,了解其中的具体用法
<table border="1" width="80%">
<tr>
<th>排列</th>
<th>排列2</th>
<th>学生编号</th>
<th>学生姓名</th>
<th>学生年龄</th>
</tr>
<c:forEach items="${requestScope.list}" var="student" step="1" begin="0" end="6" varStatus="status">
<tr>
<td>${status.index}</td>
<td>${status.count}</td>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.age}</td>
</tr>
</c:forEach>
</table>
List和Set集合能用forEach标签,思考Map集合能用forEach标签吗?
//List用ForEach标签遍历
<c:forEach items="${requestScope.list}" var="student" step="1" begin="0" end="6" varStatus="status">
<tr>
<td>${status.index}</td>
<td>${status.count}</td>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.age}</td>
</tr>
</c:forEach>
//Set用ForEach标签遍历
<c:forEach items="${requestScope.set}" var="student" varStatus="status">
<tr>
<td>${status.count}</td>
<td>${student.name}</td>
<td>${student.age}</td>
</tr>
</c:forEach>
//Map用ForEach标签遍历
<c:forEach items="${requestScope.map}" var="map">
<tr>
<td>${map.value.id}</td>
<td>${map.value.name}</td>
<td>${map.value.age}</td>
</tr>
</c:forEach>
1. 格式化标签库:对日期或者数字类型的数据进行格式化操作。
2. 函数标签库:对保存在域对象中的字符串数据进行处理。
<%@ page import="java.util.Date" %><%--
Created by IntelliJ IDEA.
User: southwind
Date: 2018/11/26
Time: 9:18 PM
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
pageContext.setAttribute("date",new Date());
%>
${date}
<hr/>
<fmt:formatDate value="${date}"></fmt:formatDate>
<hr/>
<fmt:formatDate value="${date}" pattern="yyyy-MM-dd HH:mm:ss"></fmt:formatDate>
<hr/>
<%
pageContext.setAttribute("num","32145.23464");
%>
<fmt:formatNumber value="${num}" maxFractionDigits="3" maxIntegerDigits="2"></fmt:formatNumber>
</body>
</html>
返回
<%--
Created by IntelliJ IDEA.
User: southwind
Date: 2018/11/26
Time: 9:25 PM
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
pageContext.setAttribute("info","Java,C");
%>
${fn:contains(info,"Java" )}<br/>
${fn:startsWith(info, "Ja")}<br/>
${fn:endsWith(info, "C")}<br/>
${fn:indexOf(info, "va")}<br/>
${fn:replace(info, "Java", "HTML")}<br/>
${fn:substring(info, 2, 4)}<br/>
${fn:split(info, ",")[1]}
</body>
</html>
=============================================================
结果:
true
true
true
2
HTML,C
va
C
返回
Student类
package com.chenny.test;
public class Student {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
}
StudentServlet类
package com.chenny.controller;
import com.chenny.test.Student;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class StudentServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<Student> list = new ArrayList<Student>();
list.add(new Student(1,"张三",22));
list.add(new Student(2,"李四",23));
list.add(new Student(3,"王五",24));
req.setAttribute("list",list);
req.getRequestDispatcher("index.jsp").forward(req,resp);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>student</servlet-name>
<servlet-class>com.chenny.controller.StudentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>student</servlet-name>
<url-pattern>/student.do</url-pattern>
</servlet-mapping>
</web-app>
index.jsp
<%@ page import="com.chenny.test.Student" %>
<%@ page import="java.util.List" %><%--
Created by IntelliJ IDEA.
User: 73981
Date: 2019/10/20
Time: 15:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<table border="1" width="80%">
<tr>
<th>学生编号</th>
<th>学生姓名</th>
<th>学生年龄</th>
</tr>
<c:forEach items="${list}" var="student">
<tr>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.age}</td>
</tr>
</c:forEach>
</table>
</body>
</html>