java - 将 css 文件添加到 jsp 文件中的 <head> 元素?

标签 java jsp servlets

过去一个小时我一直在网上搜索,但我不知道如何将 css 文件添加到 <head>页面的元素。

假设我有一个名为 shopping.jsp 的 jsp。在其中我有条件地包含一个名为 products.tag 的 jsp 标记文件。

我希望 products.jsp 指定一个 css 文件以添加到页面的 head 元素。如何做到这一点?

编辑

此代码是为了示例而简化的。

// shopping.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<t:standard_page>
    <jsp:body>
        <t:products product="${product}"/>
    </jsp:body>
</t:standard_page>


// products.tag
// I want to specify a css file in this tag file that will get added to the <head> element of the webpage
<%@tag description="Template for products on the shopping cart page" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@tag import="com.myapp.Product" %>
<%@attribute name="product" required="true" type="com.myapp.Product"%>

<div class="shopping-cart-row">
    <div class="product-name">${product.name}</div>
    <div class="product-quantity">${product.quantity}</div>
</div>

最佳答案

根据 HTML5, <style> elements可以出现在里面

Any element that can contain metadata elements, div, noscript, section, article, aside

所以你不需要输入<style> <head> 内的元素就像你处理 <link> 的方式一样如果您希望页面验证,请添加元素。

<style type="text/css">@import url("/path/to/stylesheet.css");</style>

从正文中可以很好地加载外部样式表。

如果它在<body>中下降很多或者有任何长时间运行的非延迟/异步 <script>元素之前,那么这些样式可能会明显晚于从 <head> 加载的样式.

关于java - 将 css 文件添加到 jsp 文件中的 <head> 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14790636/

相关文章:

java - 只捕获 RxJava 2 中特定类型的异常

java - System.out 编译器错误

java - 我可以使用什么符号表来存储约 5000 万个字符串并进行快速查找,而不会耗尽堆空间?

java - 右键单击 .jsp 文件时,“在服务器上运行”选项未出现在 Eclipse 中

java - 新的 Servlet 3.0 全局错误页面功能在 Tomcat 7 上不起作用

java - 将 Servlet 用于非 servlet 应用程序

Java重复方法实现时

java - 在 Java EE Web 应用程序中创建自定义 URL

jsp - JSTL 自定义标签

java - request.getParameter 返回空值 : servlet