Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include css and js file in every jsp page

I have common css and js files that i include in every jsp file.

So what's the best practice to include them in every page ?

I used to use <%@ include file="header.jsp" %> but I'm wondering if this is the best and clean way to proceed.

like image 811
Hayi Avatar asked Sep 14 '25 21:09

Hayi


1 Answers

I like using fragments for this, they are standard supported by JSP so no other dependencies are needed. And as you will see it will comes with lot's of other benefits.

Create a tag (parentpage.tag):

<%@tag description="Base page" pageEncoding="UTF-8" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

<%@attribute name="extra_css" fragment="true" %>
<%@attribute name="footer" fragment="true" %>
<%@attribute name="header" fragment="true" %>

<html>
<head> ....
// insert css that is needed for every page
<jsp:invoke fragment="extra_css"/>
<jsp:invoke fragment="header"/>
<jsp:doBody/>
<jsp:invoke fragment="footer"/>

Then you create individual pages that inherit from this tag

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:parentpage>

    <jsp:attribute name="extra_css">
        // custom css for this page 
    </jsp:attribute>
    <jsp:attribute name="footer">
        // footer content
    </jsp:attribute>
    <jsp:body>
       // body content
    </jsp:body>

</t:parentpage>
like image 144
Jonas Geiregat Avatar answered Sep 16 '25 10:09

Jonas Geiregat