[有书共读]JavaWeb高级编程

JavaWeb高级编程 -- 篇7

Java标准标签库

JSP标签语法中包含一些简写可以帮助轻松编写JSP。这些简写中第一个就是taglib指令。

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

指令是XML文档中引用XML命名空间的一种方式,是XMLNS技术的替代品。
指令taglib中的prefix特性代表了在JSP页面中引用标签库时使用的命名空间。
特性uri标志着TLD中为该标签库定义的URI。
所有的JSP标签都遵守相同的基本语法:

<prefix:tagname[ attribute=value[ attribute=value[ ...]]]
</prefix:tagname>

使用核心标签库

使用命名空间:

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

使用方法:

<c:out value="${someVariable}" default="value not specified" excapeXml="false" />

其中excapeXml设置为假禁止对保留的XML字符进行转义。default属性指定当value特性为null时使用的默认值。

标签<c:url>
标签<c:url>可以正确地对URL编码,并且在需要添加会话ID的时候重写它们,它还可以在JSP中输出URL。

<c:url value="http://www.example.com/test.jsp">
    <c:param name="story" value="${storyId}" />
</c:url>

<c:url>最有用的地方就在于对相对URL的编码。

标签<c:if>
标签<c:if>是一个条件标签,用于控制是否渲染特定内容。

<c:if test="${something == somethingElse}" var="itWasTrue">
    execute only if test is true
</c:if>

<c:if test="${itWasTrue}" />
    do something
</c:if>

特性test指定了一个条件,只有该条件为真时,<c:if>标签中内嵌的内容才会被执行。var特性将把测试结果保存为变量。

标签<c:choose>,<c:when>,<c:otherwise>
上述三个标签提供了复杂的if/else-if/else逻辑。

<c:choose>
    <c:when test="${something}">
        "if"
    </c:when>
    <c:when test="{somethingElse}">
        "else if"
    </c:when>
    ...
    <c:otherwise>
        "else"
    </c:otherwise>
</c:choose>

食用方法如上,类比 if-elseif-elseif-...-else 。

标签<c:forEach>
用于迭代并重复它的嵌套主题内容固定次数,或者遍历某些集合或数组。

<c:forEach var="i" begin="0" end="100" step="3">
    Line ${i} <br />
</c:forEach>

<c:forEach items="${users}" var="user">
    ${user.name} <br />
</c:forEach>

特性items中的表达式必须是一些集合、Map、Iterator、Enumeration、对象数组或者原生数组。

标签<c:redirect>
该标签将把用户重定向至另一个URL,由name属性决定。

<c:redirect url="http://www.example.com/" />  
<c:redirect url="/tickets" >
    <c:param name="action" value="view" />
</c:redirect>

标签<c:import>
该标签用于获取特性的URL资源内容。

<c:import url="/copyright.jsp" />

<c:import url="ad.jsp" context="/store" var="advertisement" scope="request">
    <c:param name="category" value="${forumCategory}" />
</c:import>

<c:import url="http://www.example.com/embeddedPlayer.do?video=f8ETe45646"
    varReader="player" charEncoding="UTF-8">
    <wrox:writeViderPlugin reader="${player}" />
</c:import>

第一个样例将应用程序本地的copyright.jsp中的内容内嵌在页面中。第二个样例将ad.jsp?category=${forumCategory}的内容保存到请求作用域的字符串变量advertisement中,并对category查询参数进行正确的编码。第三个样例获取了一些外部资源,并将它导出为名为player的Reader对象。

标签<c:set><c:remove>

<c:set>标签可以设置新的或现有的作用域变量,还可以使用它对应的标签<c:remove>从作用域中删除变量。

<c:set var="myVariable" value="hello" />
${myVariable}
<c:remove var="myVariable" scope="page" />
#Java##读书笔记#
全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务