实现此目的的最简单方法是包含/libs/foundation/global.jsp
并仅使用properties
已在范围内的对象${properties.foo}
。
在组件 jsp 的顶部包含 global.jsp,如下所示:
<%@include file="/libs/foundation/global.jsp"%>
正如文件中的注释所示,它基本上注册了 Sling (sling)、CQ (cq) 和 JSTL (c,fmt,fn) 标记库名称空间以供在 JSP 中使用。
然后,在cq:defineObjects
taglib 的帮助下,它将许多有用的对象带入范围。
<cq:defineObjects />
这是列表:
@param slingRequest SlingHttpServletRequest
@param slingResponse SlingHttpServletResponse
@param resource the current resource
@param currentNode the current node
@param log default logger
@param sling sling script helper
@param componentContext component context of this request
@param editContext edit context of this request
@param properties properties of the addressed resource (aka "localstruct")
@param pageManager page manager
@param currentPage containing page addressed by the request (aka "actpage")
@param resourcePage containing page of the addressed resource (aka "myPage")
@param pageProperties properties of the containing page
@param component current CQ5 component
@param designer designer
@param currentDesign design of the addressed resource (aka "actdesign")
@param resourceDesign design of the addressed resource (aka "myDesign")
@param currentStyle style of the addressed resource (aka "actstyle")
这意味着通过简单地使用 cq:defineObjects 标签库,您已经可以通过 JSP 表达式语言 (EL) 访问属性 ValueMap。访问 JSP 中的属性不需要额外的转换。
<c:out value="${properties.foo}" />
要访问您自己的 Java taglib 或 bean 中的属性,您只需使用标准 JSTL 标记将适当的对象传递给您的代码。您可以传递整个请求、当前资源或仅传递属性。传递整个请求使您的 Java 代码可以访问当前资源和由 cq:defineObjects 标签库创建的所有对象,包括属性 ValueMap。
在 JSP 中:
<jsp:useBean id="mybean" scope="request" class="com.my.impl.TheBean">
<jsp:setProperty name="mybean" property="slingRequest" value="${slingRequest}"/>
<jsp:setProperty name="mybean" property="resource" value="${resource}"/>
<jsp:setProperty name="mybean" property="properties" value="${properties}"/>
</jsp:useBean>
在豆中:
public void setSlingRequest(final SlingHttpServletRequest slingRequest) {
this.slingRequest = slingRequest;
// Use the one created by cq:defineObjects
this.properties = (ValueMap)this.slingRequest.getAttribute("properties");
// OR adapt the resource
this.properties = this.slingRequest.getResource().adaptTo(ValueMap.class);
}
public void setResource(final Resource resource) {
this.resource = resource;
this.properties = this.resource.adaptTo(ValueMap.class);
}
public void setProperties(final ValueMap properties) {
this.properties = properties;
}