【问题标题】:include css file in jsp only if it exist仅当存在时才在 jsp 中包含 css 文件
【发布时间】:2024-01-14 20:38:01
【问题描述】:

我正在尝试使用默认 css 设计一个应用程序。我想要一个选项,我可以在其中包含更改默认皮肤的新 css(自定义)文件。

我可以通过在我的 jsp 页面中同时引用(自定义和默认 css)来实现这一点,默认将始终存在,并且可以为不同的用户加载自定义 css。

在不存在自定义文件的场景中,我在浏览器控制台中收到“找不到文件”(404) 错误。有没有办法(或 jstl 标记)在将自定义文件包含在 jsp 中之前检查它是否存在?

【问题讨论】:

  • 检查一下,足够接近:*.com/questions/2624657/…
  • catch 块不会解决我的问题,因为我使用 html 'link' 标签来包含 css 文件。我可以使用 jstl 包含 css 吗?

标签: jsp jstl


【解决方案1】:

直接使用 JSTL 不容易做到这一点。我建议您使用一个类来检查文件是否存在并返回一个布尔值。这将允许您使用 JSTL 选择或 if 语句来实现您的目标。

可以通过多种方式使用类文件。我可能会编写一个实用程序类并创建一个自定义标记库,可以使用 EL/JSTL 调用它来完成这项工作。您可以在此处查看此类方法的示例:How to call a static method in JSP/EL?

以下是我过去用来检查 Tomcat 中文件的文件实用程序类的示例。

package com.mydomain.util;

public class FileUtil implements Serializable {

    public static boolean fileExists(String fileName){
        File f = new File(getWebRootPath() + "css/" + fileName);
        return f.exists();
    }

    private static String getWebRootPath() {
        return FileUtil.class.getProtectionDomain().getCodeSource().getLocation().getPath().split("WEB-INF/")[0];
    }
}

然后在 /WEB-INF/functions.tld 中,创建您的定义:

<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    version="2.0">

    <tlib-version>2.0</tlib-version>
    <uri>http://www.your-domain.com/taglib</uri>

    <function>
        <name>doMyStuff</name>
        <function-class>com.mydomain.util.FileUtil</function-class>
        <function-signature>
             java.lang.Boolean fileExists(java.lang.String)
        </function-signature>
    </function>
</taglib>

JSP 中的:

<%@ taglib prefix="udf" uri="http://www.your-domain.com/taglib" %>

 <c:if test="${udf:fileExists('my.css')}">
      <!-- do magic  -->
 </c:if>

【讨论】:

  • 我按照你的描述做了我自己的实现。谢谢