S4beR
S4beR

Reputation: 1847

include css file in jsp only if it exist

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.

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.

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 ?

Upvotes: 6

Views: 5051

Answers (1)

Russell Shingleton
Russell Shingleton

Reputation: 3196

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.

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?

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];
    }
}

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>

The in the JSP:

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

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

Upvotes: 7

Related Questions