使用JSTL需要在JSP页面上方进行导入
<%@ taglib prefix="页面中表示JSTL的变量名" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="页面中表示JSTL的变量名" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="页面中表示JSTL的变量名" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="页面中表示JSTL的变量名" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@ taglib prefix="页面中表示JSTL的变量名" uri="http://java.sun.com/jsp/jstl/xml" %>
这里默认加载core标签库,变量名为jstl:
<%@ taglib prefix="jstl" uri="http://java.sun.com/jsp/jstl/core" %>
JSTL有很多标签,由于日常开发过程中很少用到,这里只记录自己常用的一些标签。
JSTL标签:<jstl:if>
该标签是一个容器标签,用于有条件的执行代码。尝配合EL表达式来使用。
<jstl:if test="" scope="" var=""> </jstl:if>
参数 类型 描述 是否可以引用EL表达式 test boolean 条件表达式 可以 var String 指定存储test属性判断结果的变量名称 不可以 scope String 指定变量的范围 不可以
JSTL标签: <jstl:forEach>
<jstl:forEach items="" var="" varStatus="" begin="" end=""> </jstl:forEach>
参数 类型 描述 是否可以引用EL表达式 items 数组、集合类、字符串、枚举 将要迭代的集合对象 可以 var String 指定将当前迭代到的元素保存到作用域中的属性名称 不可以 varStatus String 制定将代表当前迭代状态信息的对象保存到page作用域的属性名称 不可以 begin int 指定开始遍历的索引 不可以 end int 指定结束遍历的索引 不可以 关于varStatus属性的使用
<jstl:forEach items="" var="" varStatus="varIndex" begin="" end=""> <jstl:if items="${varIndex.index == 1}"> //index属性返回值为当前循环的索引值 //返回类型为int </jstl:if> <jstl:if items="${varIndex.count == 1}"> //count属性返回值为当前循环次数 //返回类型为int </jstl:if> <jstl:if items="${varIndex.first == true}"> //first属性返回值为是否为第一次循环 //返回类型为boolean </jstl:if> <jstl:if items="${varIndex.last == true}"> //last属性返回值为是否为最后一次循环 //返回类型为boolean </jstl:if> </jstl:forEach>
JSTL标签:<jstl:formatDate>
//需要用到fmt标签库 <%@ taglib prefix="jstlFmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <jstlFmt:formatDate value="" pattern=""/>
参数 类型 描述 是否可以引用EL表达式 value Java.util.Date 指定被格式化的日期 可以 pattern String 格式化样式 可以
JSP标签:<jsp:forward>
<jsp:forward page="要跳转的路径"></jsp:forward> //实例: <c:if test="${list==null}">//如果list变量值为空 <jsp:forward page="GetList"></jsp:forward>//跳转到GetList.java为list赋值 </c:if> <c:forEach items="${list}" var="listText">//对list集合进行迭代 <h1>${listText}</h1>//输出 </c:forEach>