3

我有一个名为 header.jsp 的 JSP 文件,它看起来像这样。

<%@ taglib prefix="c" uri="/c" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>

然后我有一个看起来像这样的内容片段。

<jsp:include page="../header.jsp" />
My Page Content Here.

如果该内容片段具有某些依赖项,例如 CSS 和 Javascript 包含必须进入 head 标签内,我如何将它们包含在其中?每个片段可能有自己的一组不同的 CSS 和 Javascript 文件,我不想将我可能使用的每个可能的 CSS 和 Javascript 文件都包含在每个页面的标题中。处理这个问题的正确方法是什么?我是一家初创公司的愚蠢实习生,所以请原谅我的无知。提前谢谢你。

4

1 回答 1

2

It's easy, you can do the following by using <jsp:invoke /> tag instead of the <include /> tag. It's new for jsp 2.0 and allows you to take some fragments from one page to another, making very easy the task of building templates. You can check a tutorial here.

And this is the way to solve your problem: Create a tag folder and put this in it.

template.tag

<%@tag description="Main template of the page" pageEncoding="UTF-8" trimDirectiveWhitespaces="true" %>

<%@attribute name="header" fragment="true" required="false" %>
<html>
    <head>
        ...some css and javasctipt used on all the pages...
        <!-- Custom css and javascript for one page -->
        <jsp:invoke fragment="header"/>
    </head>
    <body>
        <jsp:doBody />
    </body>
</html>

Use the previous template on your page by including the tag folder:

useOfTemplate.jsp

<%@page contentType="text/html" pageEncoding="UTF-8" %>

<%@taglib prefix="custom" tagdir="/WEB-INF/tags" %>

<custom:template>
    <jsp:attribute name="header">
        ...Here you can include your custom css and javascript for this page...
    </jsp:attribute>
    <jsp:body>
        ...here comes the info of the page...
    </jsp:body>
</custom:template>
于 2013-03-24T18:23:33.380 回答