仅在jsp中包含css文件(如果存在) [英] include css file in jsp only if it exist

查看:203
本文介绍了仅在jsp中包含css文件(如果存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to design an application with default css. I want to have an option where i can include new css (custom) file which change the default skin.

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

I can acheive this by referring both (custom and default css) in my jsp page where default will be always present and custom css may be loaded for different users.

在不存在自定义文件的情况下,我在浏览器控制台中收到找不到文件"(404)错误.在我将自定义文件包含在jsp中之前,是否有办法(或jstl标记)检查自定义文件是否存在?

In scenations where custom file is not present I receive 'File Not Found' (404) error in browser console. Is there a way (or jstl tag) to check whether custom file exists before I include it in jsp ?

推荐答案

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

This is not easily done with JSTL directly. I would suggest you use a class to check if the file exists and return a boolean value. This would allow you to use a JSTL choose or if statement to accomplish your goal.

可以通过多种方式使用类文件.我可能会写一个实用程序类并创建一个自定义taglib,可以使用EL/JSTL调用它来完成这项工作.您可以在此处查看这种方法的示例:如何在JSP/EL中调用静态方法?

Using a class file can be approached in multiple ways. I would probably write a utility class and create a custom taglib which can be called using EL/JSTL to do the job. You can see an example of this type of approach here: How to call a static method in JSP/EL?

以下是我过去用来检查Tomcat中文件的文件实用工具类的示例.

The following is an example of a file utility class that I've used in the past to check for files in 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中,创建您的定义:

Then inside /WEB-INF/functions.tld, create your definition:

<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>

这篇关于仅在jsp中包含css文件(如果存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆