增强的 jsp:include 实现

2024-05-02

一直困扰我的事情之一<jsp:include..>的问题是不可能将非字符串值作为页面的不同输入传递到包含的页面中。例如,我希望能够执行以下操作:

<c:forEach var="item" items="${listOfItems}">
    <jsp:include page="mypage.jsp">
        <jsp:attribute name="item" value="${item}/>
    </jsp:include>
</c:forEach>

这个想法是,通过声明作为 jsp:include 节点内的属性传入的项目,代码可以清楚地表明意图是什么...将该参数提供给包含的页面。

当前可用于执行此操作的唯一机制是“全局”定义属性,然后让包含的页面从全局空间读取它。不幸的是,这失去了使用

有谁知道包含机制的实现,该机制执行 jsp:include 的功能,但允许传入非字符串值?或者,如果没有,我会接受其他想法,以保持相同的意图目标和易于调试。

作为旁注,我希望看到一个内置的“捕获”机制,用于当包含的页面抛出错误时:

<abc:include page="mypage">
    <abc:param name="something" value="some string value"/>
    <abc:attribute name="somethingelse" value="${nonStringValue}"/>
    <abc:catch var="ex">
        The page failed, so the content it generated will not be sent to the output
        stream. Instead, we can collapse the part of the page that it's content
        would be... possibly putting a comment in the page with
        <!-- There was an exception generating this module: 
             <c:out value="${ex.getMessage}/>
          -->
    </abc:catch>
</abc:include>

来自 JSTL 规范:

嵌套作用域变量仅在操作主体内可见并存储 在“页面”范围内。

您可以通过传递对象引用request scope.

标准包含.jsp:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:out value="${foo}" />

标准操作.jsp:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
  //evil scriptlet
  request.setAttribute("mylist", java.util.Arrays.asList("bar", "baz"));
%>
<c:forEach items="${mylist}" var="foo">
    <c:set var="foo" scope="request" value="${foo}" />
    <jsp:include page="standardInclude.jsp" />
    <c:set var="foo" scope="request" value="${null}" />
</c:forEach>

您可以使用catch http://download.oracle.com/docs/cd/E17802_01/products/products/jsp/jstl/1.1/docs/tlddocs/c/catch.html标记来捕获异常。

投掷者.jsp:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:out value="OK: ${foo}" />
<%
  //evil scriptlet
  if ("bar".equals(request.getAttribute("foo")))
    throw new java.io.IOException("oops");
%>

捕手.jsp:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
  //evil scriptlet
  request.setAttribute("mylist", java.util.Arrays.asList("bar", "baz"));
%>
<c:forEach items="${mylist}" var="foo">
    <br />
    <c:set var="foo" scope="request" value="${foo}" />
    <c:catch var="ex">
        <jsp:include page="thrower.jsp" />
    </c:catch>
    <c:if test="${ex ne null}">
        <c:out value="Error for ${foo}" />
    </c:if>
    <c:set var="foo" scope="request" value="${null}" />
</c:forEach>

这将发出:

Error for bar 
OK: baz 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

增强的 jsp:include 实现 的相关文章

随机推荐