JSTL

JSTL, JSP Standard Tag Library. 使用 JSTL,需要 servlet 版本高于或等于2.4,这个版本在 web.xml 可配置,需要特别注意。JSTL 通常和 EL 结合使用。

如果 java webapp 要使用 JSTL 则需要添加两个 jar 包: jstl api, jstl impl,它们和从前的叫法对应关系如下:

  • jstl-api 相当于从前的 jstl
  • jstl-impl 相当于从前的 standard.jar

这两个 jar 包可以在这里下载:http://jstl.java.net/download.html

添加后,可能是这个样子:

如果使用 maven,相关的配置可参《配置 jstl 的 maven dependency

关于 JSTL 的使用

要使用 JSTL,需要根据需要添加类似下面的信息:

  • <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  • <%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>
  • <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
  • <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
  • <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

一般,sql 的标签库是不用的——但有些比较老旧的系统还有用到。

这里是一个 JSTL and EL 结合使用的例子:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  
<c:set var="itemClass" value='${4 % 2 ==0 ? "even" :"odd"}'/>
${itemClass}
abc
<c:out value='${3 % 2 ==0? "" :"odd"}'/>

输出:

even abc odd