【问题标题】:Importing CSS in JSP tags在 JSP 标签中导入 CSS
【发布时间】:2011-12-08 19:05:10
【问题描述】:

有哪些方法(如果有)可以从

中调用的 JSP 标记链接或导入样式表?如果我可以将所有必要的导入封装在 JSP 标记中,那就太好了。

当前状态

index.jsp:

<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="x" tagdir="/WEB-INF/tags" %>
<html>
    <head>
        <!-- we have to know what css file somecontent uses and include it here -->
        <!-- the tag below prints <link rel="/somecontent.css"... /> but makes sure this url is only included once -->
        <x:requireOnce loc="/somecontent.css" type="css" />
    </head>
    <body>
        <x:somecontent />
    </body>
</html>

目标

index.jsp:

<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="x" tagdir="/WEB-INF/tags" %>
<html>
    <head>
        <%-- nothing for somecontent tag here --%>
    </head>
    <body>
        <x:somecontent />
        ...
    </body>
</html>

somecontent.tag:

<%@ tag description="some independent content" %>
<%@ taglib prefix="x" tagdir="/WEB-INF/tags" %>
<%-- the inline attribute will indicate that it is in the body and shouldn't use <link> which won't work here --%>
<x:requireOnce loc="/somecontent.css" type="css" inline="true" />
<%-- this will print <script type="text/javascript" src="/somecontent.js" ...></script> --%>
<x:requireOnce loc="/somecontent.js" type="js" />
...

有没有办法在 JspWriter 中保留对 head 标记中位置的引用,并在必要时在其中插入内容,即新的链接标记?

理想情况下,我不想内联样式表的内容或使用 javascript 来包含样式表。希望@import、 或一些 JSP 魔法有什么用处……有什么想法吗?

【问题讨论】:

  • 您基本上是在重新发明一些基于组件的 MVC 框架中已经存在的东西,例如为此目的有一个 &lt;h:outputStylesheet&gt; 标记的 JSF(以及用于 JS 的 &lt;h:outputScript&gt;)。我建议看一下,而不是重新发明轮子。
  • 谢谢,BalusC。我不确定我们是否可以切换到 JSF。你知道有什么方法可以只使用 JSP 和 Spring MVC 来做同样的事情吗?
  • 一切皆有可能。在某些情况下,您只需要自己编写比其他情况更多的代码。抱歉,我无法详细发布答案,因为我不是很喜欢 JSP 标签和 Spring MVC。

标签: html css jsp jsp-tags


【解决方案1】:

您可以按照 SiteMesh 所做的那样做一些事情。

每个requireOnce 标签只会将要链接的文件放在文件列表中,并存储在请求属性中。 servlet 过滤器将缓冲整个响应,并在完成时重写它,并重写头部部分以包含所有链接。

【讨论】:

  • 谢谢 JB,这听起来可行。这可能是我最终的结果。
  • 采用了这个解决方案。不幸的是,在没有 JSF 的情况下,我不得不编写比预期更多的代码来重新发明这个轮子,但这似乎是唯一的方法。
猜你喜欢
  • 2013-05-27
  • 2016-12-19
  • 2019-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
  • 1970-01-01
  • 2016-01-25
相关资源
最近更新 更多