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 ?
To include CSS or JS in a JSP page, you can use JSTL tag c:url or Spring tag spring:url . 3.1 JSTL tag c:url example.
The page directive is used to provide instructions to the container that pertain to the current JSP page. You may code the page directives anywhere in your JSP page. By convention, page directives are coded at the top of the JSP page. Following is the basic syntax of page directive − <%@ page attribute = "value" %>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With