how2j.cn

相关下载
文件名 文件大小
standard.jar 384k
jstl.jar 20k

工具版本兼容问题
JSTL JSP Standard Tag Library 标准标签库

JSTL允许开人员可以像使用HTML标签 那样在JSP中开发Java功能。

JSTL库有core, i18n, fmt, sql 等等。

i18n和sql用的很少,core和fmt在工作中会用到,本章节主要讲解core和fmt

步骤 1 : 导入jar包   
步骤 2 : set out remove   
步骤 3 : if else   
步骤 4 : choose   
步骤 5 : forEach   
步骤 6 : forTokens   
步骤 7 : fmt:formatNumber 格式化数字   
步骤 8 : fmt:formatDate 格式化日期   
步骤 9 : fn:   

步骤 1 :

导入jar包

为了能够在JSP 中使用JSTL,首先需要两个jar包,分别是jstl.jar 和standard.jar

可以在右侧下载

把这两个jar包放在web/WEB-INF/lib 下
导入jar包
步骤 2 :

set out remove

在页面中使用JSTL需要在jsp中 通过指令进行设置


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

prefix="c" 表示后续的标签使用都会以<c: 开头

<c:set var="name" value="${'gareen'}" scope="request" />

在作用域request中设置name,相当于
<%request.setAttribute("name","gareen")%>


<c:out value="${name}" />

相当于 <%=request.getAttribute("name")%>


<c:remove var="name" scope="request" />

在作用域request中删掉name,相当于
<%request.removeAttribute("name")%>

作用域可以是pageContext, request, session, application, 参考 作用域
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <c:set var="name" value="${'gareen'}" scope="request" /> 通过标签获取name: <c:out value="${name}" /> <br> <c:remove var="name" scope="request" /> <br> 通过标签获取name: <c:out value="${name}" /> <br>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

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

<c:set var="name" value="${'gareen'}" scope="request" />

通过标签获取name: <c:out value="${name}" /> <br>

<c:remove var="name" scope="request" /> <br>

通过标签获取name: <c:out value="${name}" /> <br>
步骤 3 :

if else

JSTL通过<c:if test=""> 进行条件判断

但是JSTP没有<c:else,所以常用的办法是在<c:if的条件里取反

配合if使用的还有通过empty进行为空判断
empty可以判断对象是否为null,字符串长度是否为0,集合长度是否为0
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <c:set var="hp" value="${10}" scope="request" /> <c:if test="${hp<5}"> <p>这个英雄要挂了</p> </c:if> <c:if test="${!(hp<5)}"> <p>这个英雄觉得自己还可以再抢救抢救</p> </c:if> <% pageContext.setAttribute("weapon", null); pageContext.setAttribute("lastwords", ""); pageContext.setAttribute("items", new ArrayList()); %> <c:if test="${empty weapon}"> <p>没有装备武器</p> </c:if> <c:if test="${empty lastwords}"> <p>挂了也没有遗言</p> </c:if> <c:if test="${empty items}"> <p>物品栏为空</p> </c:if>
步骤 4 :

choose

虽然JSTL没有提供else标签,但是提供了一个else功能的标签

<c:choose>
<c:when test="${hp<5}">

</c:when>
<c:otherwise>

</c:otherwise>
</c:choose>


我个人觉得看上去繁琐,还是习惯用<c:if test="!" 来表示else
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <c:set var="hp" value="${3}" scope="request" /> <c:choose> <c:when test="${hp<5}"> <p>这个英雄要挂了</p> </c:when> <c:otherwise> <p>这个英雄觉得自己还可以再抢救抢救</p> </c:otherwise> </c:choose>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8" import="java.util.*"%>

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

<c:set var="hp" value="${3}" scope="request" />

<c:choose>
    <c:when test="${hp<5}">
		<p>这个英雄要挂了</p>
	</c:when>
	<c:otherwise>
		<p>这个英雄觉得自己还可以再抢救抢救</p>
	</c:otherwise>
</c:choose>
步骤 5 :

forEach

可以在JSP中使用for循环,但是其可读性很差。 借助JSTL的c:forEach标签,可以改善可读性

在本例中,分别使用for循环和<c:forEach标签来演示遍历一个List的区别


<c:forEach items="${heros}" var="hero" varStatus="st" >

items="${heros}" 表示遍历的集合
var="hero" 表示把每一个集合中的元素放在hero上
varStatus="st" 表示遍历的状态
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <% List<String> heros = new ArrayList<String>(); heros.add("塔姆"); heros.add("艾克"); heros.add("巴德"); heros.add("雷克赛"); heros.add("卡莉丝塔"); request.setAttribute("heros",heros); %> <!-- 使用jsp中的for循环来遍历List --> <table width="200px" align="center" border="1" cellspacing="0"> <tr> <td>编号</td> <td>英雄</td> </tr> <% int i =0; for (String hero : heros) { i++; %> <tr> <td><%=i%></td> <td><%=hero%></td> </tr> <%}%> </table> <br> <!-- 使用JSTL中的c:forEach 循环来遍历List --> <table width="200px" align="center" border="1" cellspacing="0"> <tr> <td>编号</td> <td>英雄</td> </tr> <c:forEach items="${heros}" var="hero" varStatus="st" > <tr> <td><c:out value="${st.count}" /></td> <td><c:out value="${hero}" /></td> </tr> </c:forEach> </table>
步骤 6 :

forTokens

<c:forTokens专门用于字符串拆分,并且可以指定多个分隔符
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <c:set var="heros" value="塔姆,艾克;巴德|雷克赛!卡莉丝塔" /> <c:forTokens items="${heros}" delims=":;|!" var="hero"> <c:out value="${hero}" /> <br /> </c:forTokens>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 
<c:set var="heros" value="塔姆,艾克;巴德|雷克赛!卡莉丝塔" /> 

<c:forTokens items="${heros}" delims=":;|!" var="hero">
	<c:out value="${hero}" /> <br />
</c:forTokens>
步骤 7 :

fmt:formatNumber 格式化数字

fmt 标签常用来进行格式化,其中fmt:formatNumber用于格式化数字
使用之前要加上

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


<fmt:formatNumber type="number" value="${money}" minFractionDigits="2"/>

<fmt:formatNumber 表示格式化数字
minFractionDigits 小数点至少要有的位数
maxFractionDigits 小数点最多能有的位数
fmt:formatNumber 格式化数字
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix='fmt' %> <c:set var="money" value="888.8" /> <c:set var="pi" value="3.1415926" /> 最少两个小数点: <fmt:formatNumber type="number" value="${money}" minFractionDigits="2"/> <br> 最多两个小数点: <fmt:formatNumber type="number" value="${pi}" maxFractionDigits="2" />
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
    
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix='fmt' %>  

<c:set var="money" value="888.8" />
<c:set var="pi" value="3.1415926" />
最少两个小数点:
<fmt:formatNumber type="number" value="${money}" minFractionDigits="2"/>
<br>
最多两个小数点:
<fmt:formatNumber type="number" value="${pi}" maxFractionDigits="2" />
步骤 8 :

fmt:formatDate 格式化日期

fmt 标签常用来进行格式化,其中fmt:formatDate 用于格式化日期
fmt:formatNumber 格式化数字一样,使用之前要加上

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


<fmt:formatDate value="${now}" pattern="G yyyy年MM月dd日 E"/>
<fmt:formatDate value="${now}" pattern="a HH:mm:ss.S z"/>
<fmt:formatDate value="${now}" pattern="yyyy-MM-dd HH:mm:ss"/>

<fmt:formatDate 表示格式化日期
yyyy 表示年份
MM 表示月份
dd 表示日期
E 表示星期几

a 表示是上午还是下午
HH 表示小时
mm 表示分钟
ss 表示秒
S 表示毫秒
z 表示时区
fmt:formatDate 格式化日期
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix='fmt' %> <% Date now = new Date(); pageContext.setAttribute("now",now); %> 完整日期: <fmt:formatDate value="${now}" pattern="G yyyy年MM月dd日 E"/><br> 完整时间: <fmt:formatDate value="${now}" pattern="a HH:mm:ss.S z"/><br> 常见格式: <fmt:formatDate value="${now}" pattern="yyyy-MM-dd HH:mm:ss"/>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
    
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix='fmt' %>  

<%
	Date now = new Date();
	pageContext.setAttribute("now",now);
%>

完整日期: <fmt:formatDate value="${now}" pattern="G yyyy年MM月dd日 E"/><br>
完整时间: <fmt:formatDate value="${now}" pattern="a HH:mm:ss.S z"/><br>
常见格式: <fmt:formatDate value="${now}" pattern="yyyy-MM-dd HH:mm:ss"/>
步骤 9 :

fn:

fn标签提供各种实用功能,首先使用之前使用加入如下指令

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

用法举例:

${fn:substring(name, 0, 5)}

获取name的前5位
"); window.frames["iframe_show2092"].document.write(decodeHtml($("textarea#stepcodeTextarea2092").val())); window.frames["iframe_show2092"].document.close(); $(window.frames["iframe_show2092"]).load(function(){ $("#iframe_show2092").height($("#iframe_show2092").contents().find("body").height()+showittryitheight); }); $("#iframe_show2092").height($("#iframe_show2092").contents().find("body").height()+showittryitheight); setTimeout(function(){ },500); });
<style> td{ border:1px solid silver; font-size:12px; padding:5px; } table{ border-collapse:collapse } </style> <table > <tbody> <tr> <td><strong>函数</strong></td> <td><strong>描述</strong></td> </tr> <tr> <td><p>fn:contains(string, substring)</p></td> <td><p>如果参数string中包含参数substring,返回true</p></td> </tr> <tr> <td><p>fn:containsIgnoreCase(string, substring)</p></td> <td><p>如果参数string中包含参数substring(忽略大小写),返回true</p></td> </tr> <tr> <td><p>fn:endsWith(string, suffix)</p></td> <td><p>如果参数 string 以参数suffix结尾,返回true</p></td> </tr> <tr> <td><p>fn:escapeXml(string)</p></td> <td><p>将有特殊意义的XML (和HTML)转换为对应的XML character entity code,并返回</p></td> </tr> <tr> <td><p>fn:indexOf(string, substring)</p></td> <td><p>返回参数substring在参数string中第一次出现的位置</p></td> </tr> <tr> <td><p>fn:join(array, separator)</p></td> <td><p>将一个给定的数组array用给定的间隔符separator串在一起,组成一个新的字符串并返回。</p></td> </tr> <tr> <td><p>fn:length(item)</p></td> <td><p>返回参数item中包含元素的数量。参数Item类型是数组、collection或者String。如果是String类型,返回值是String中的字符数。</p></td> </tr> <tr> <td><p>fn:replace(string, before, after)</p></td> <td><p>返回一个String对象。用参数after字符串替换参数string中所有出现参数before字符串的地方,并返回替换后的结果</p></td> </tr> <tr> <td><p>fn:split(string, separator)</p></td> <td><p>返回一个数组,以参数separator 为分割符分割参数string,分割后的每一部分就是数组的一个元素</p></td> </tr> <tr> <td><p>fn:startsWith(string, prefix)</p></td> <td><p>如果参数string以参数prefix开头,返回true</p></td> </tr> <tr> <td><p>fn:substring(string, begin, end)</p></td> <td><p>返回参数string部分字符串, 从参数begin开始到参数end位置,包括end位置的字符</p></td> </tr> <tr> <td><p>fn:substringAfter(string, substring)</p></td> <td><p>返回参数substring在参数string中后面的那一部分字符串</p></td> </tr> <tr> <td><p>fn:substringBefore(string, substring)</p></td> <td><p>返回参数substring在参数string中前面的那一部分字符串</p></td> </tr> <tr> <td><p>fn:toLowerCase(string)</p></td> <td><p>将参数string所有的字符变为小写,并将其返回</p></td> </tr> <tr> <td><p>fn:toUpperCase(string)</p></td> <td><p>将参数string所有的字符变为大写,并将其返回</p></td> </tr> <tr> <td><p>fn:trim(string)</p></td> <td><p>去除参数string 首尾的空格,并将其返回</p></td> </tr> </tbody> </table>
"); window.frames["iframe2092"].document.write(decodeHtml(code2092)); window.frames["iframe2092"].document.close(); //load和下面的非load必需并存,因为如果代码用到了jquery就必须使用load的方式 $(window.frames["iframe2092"]).load(function(){ $("#iframe2092").height($("#iframe2092").contents().find("body").height()+showittryitheight); }); $("#iframe2092").height($("#iframe2092").contents().find("body").height()+showittryitheight); alreadyWriteCode2092 = code2092; $("#rendering2092").hide(); $("#rendered2092").show(); } var tRereshRetry2DemoPanel2092 = setInterval(rereshRetry2DemoPanel2092,1000); var binded2092 = false; $("textarea#stepcodeTextarea2092").keyup(function(){ if(!binded2092){ $(window).bind('beforeunload',function(){ binded2092 = true; return "xxxx"; }); } var newCode = $(this).val() code2092 = newCode; /*below code is replaced by function rereshRetry2DemoPanel()*/ // if(code2092!=newCode){ // window.frames["iframe2092"].document.write("
"); // window.frames["iframe2092"].document.write(decodeHtml($("textarea#stepcodeTextarea2092").val())); // window.frames["iframe2092"].document.close(); // $(window.frames["iframe2092"]).load(function(){ // $("#iframe2092").height($("#iframe2092").contents().find("body").height()+showittryitheight); // }); // code2092 = newCode; // } }); $(".tryButton2092").click(function(){ $("#tryDiv2092").show(); $("#stepcodeTextarea2092").focus(); $("#stepcodeTextarea2092").height(200); $("#iframe2092").height(0); window.frames["iframe2092"].document.write("
"); window.frames["iframe2092"].document.write(decodeHtml($("textarea#stepcodeTextarea2092").val())); window.frames["iframe2092"].document.close(); //load和下面的非load必需并存,因为如果代码用到了jquery就必须使用load的方式 $(window.frames["iframe2092"]).load(function(){ $("#iframe2092").height($("#iframe2092").contents().find("body").height()+showittryitheight); }); $("#iframe2092").height($("#iframe2092").contents().find("body").height()+showittryitheight); this.scrollIntoView(true); editor2092.focus(); editor2092.setSize(null, "250"); $("#rendering2092").hide(); $("#rendered2092").hide(); }); var mixedMode = { name: "htmlmixed", scriptTypes: [{matches: /\/x-handlebars-template|\/x-mustache/i, mode: null}, {matches: /(text|application)\/(x-)?vb(a|script)/i, mode: "vbscript"}] }; var editor2092 = CodeMirror.fromTextArea(document.getElementById("stepcodeTextarea2092"), { lineNumbers: true, styleActiveLine: true, matchBrackets: true, mode:"text/html", theme:"eclipse", selectionPointer: true, lineWrapping: true, extraKeys: { "Alt-/": "autocomplete", "Ctrl-F": "findPersistent", "F8": function(cm) { cm.setOption("fullScreen", !cm.getOption("fullScreen")); }, "Esc": function(cm) { if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false); } } }); editor2092.on("change",function(doc){ if(!binded2092){ $(window).bind('beforeunload',function(){ binded2092 = true; return "xxxx"; }); } var newCode = doc.getValue(); code2092 = newCode; $("textarea#stepcodeTextarea2092").val(newCode); if(alreadyWriteCode2092!=code2092){ lastModifedTime2092 = new Date().getTime(); $("#rendering2092").show(); $("#rendered2092").hide(); } // alert(doc.getValue()); }); $(".CodeMirror").addClass("form-control"); // var editor2092 = CodeMirror.fromTextArea(, { // lineNumbers: true, // styleActiveLine: true, // matchBrackets: true, // theme:"eclipse", // }); editor2092.on("change",function(doc){ // alert(doc.getValue()); }); $("#tryDiv2092").hide(); }); $("div.codemirrorTips span").addClass("glyphicon glyphicon-asterisk");


源代码
1. 双击选中单词 2. 三击选中整行 3. CTRL+F 查找 4. F8 全屏编辑,再次点击恢复
渲染中 渲染完成
效果


HOW2J公众号,关注后实时获知布最新的教程和优惠活动,谢谢。


关于 J2EE-JSP-JSTL 的提问

尽量提供截图代码异常信息,有助于分析和解决问题。 也可进本站QQ群交流: 620943819
提问尽量提供完整的代码,环境描述,越是有利于问题的重现,您的问题越能更快得到解答。
对教程中代码有疑问,请提供是哪个步骤,哪一行有疑问,这样便于快速定位问题,提高问题得到解答的速度
在已经存在的几千个提问里,有相当大的比例,是因为使用了和站长不同版本的开发环境导致的,比如 jdk, eclpise, idea, mysql,tomcat 等等软件的版本不一致。
请使用和站长一样的版本,可以节约自己大量的学习时间。 站长把教学中用的软件版本整理了,都统一放在了这里, 方便大家下载: http://how2j.cn/k/helloworld/helloworld-version/1718.html

上传截图