Spring Boot Thymeleaf CSS JS with Example





Hey guys in this post, we will discuss adding static resources like CSS and Javascript to the Thymeleaf template engine with Spring boot.

Overview


Thymeleaf is a Java XML/XHTML/HTML5 template engine that can work both in web and non-web environments. It is better suited for serving XHTML/HTML5 at the view layer of MVC-based web applications, but it can process any XML file even in offline environments. It provides full Spring Framework integration.

In this post, we will discuss the different ways of adding CSS style and javascript to the Thymeleaf template engine

Different ways to add CSS and Javascript


There are 2 ways to add CSS and JS files to the Thymeleaf template.

  • Adding CSS and javascript files to the static folder and reference it to the Thymeleaf templates
  • Use CDN links to reference it to the Thymeleaf templates.

Add CSS and JS files to the static folder


The one way to add CSS and JS files is to add them to the static folder of src/main/resources and reference it to the Thymeleaf template.

<link rel="stylesheet" th:href="@{/home.css}" />

Here @{} is the way of linking URL in Thymeleaf.

Use CDN links


Another way is to use CDN links to reference it to the Thymeleaf template.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" />

The CDN link goes between the <head> section of the templates.

Complete example


Let’s create a step-by-step spring boot project and display the current date and time. Also, add the CSS styles to the application.

Create spring boot project


There are many different ways to create a spring boot application, you can follow the below articles to create one –

>> Create spring boot application using Spring initializer
>> Create spring boot application in Spring tool suite [STS]
>> Create spring boot application in IntelliJ IDEA

Add maven dependencies


Open pom.xml and add the following dependencies –

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>in.bushansirgur</groupId>
	<artifactId>springboot-thymeleaf</artifactId>
	<version>v1</version>
	<name>springboot-thymeleaf</name>
	<description>Spring boot thymeleaf</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

spring-boot-starter-web dependency for building web applications using Spring MVC. It uses the tomcat as the default embedded container. We have added the spring-boot-starter-thymeleafdependency for Thymeleaf support. We have also added the spring-boot-devtools dependency for automatic reloads or live reload of applications.



Create a controller


Create HomeController.java inside the in.bushansirgur.springboot.controller package and add the following content

package in.bushansirgur.springboot.controller;

import java.util.Date;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HomeController {
	
	@GetMapping("/datetime")
	public ModelAndView getCurrentDateAndTime() {
		ModelAndView mav = new ModelAndView("home");
		mav.addObject("currentDateAndTime", new Date());
		return mav;
	}
}

We have created a handler method getCurrentDateAndTime() which is mapped to the URI /datetime which is annotated with @GetMapping annotation.

Create a CSS file


Create home.css inside the static folder of src/main/resources and add the following content.

p {
	color: red;
	font-style: italic;
}

This is pretty straightforward, we have added style to the <p> element.

Create a Javascript file


Create home.js inside the static folder of src/main/resources and add the following content.

alert("script file is loading...");

This is pretty straightforward, we are displaying the alert box, as soon the template is loaded.

Create a view


Inside the templates folder, create home.html file and add the following content

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" 
		integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" 
		crossorigin="anonymous">
<link rel="stylesheet" th:href="@{/home.css}" />
</head>
<body>
	<div class="container">
		<p th:text="'The current date and time is '+${currentDateAndTime}"></p>
	</div>
	
	<script th:src="@{/home.js}"></script>
</body>
</html>

Within the <head> section, we are referencing the home.css file which is present in the static folder of src/main/resources

Next, we are referencing the Bootstrap library using the CDN link which also goes inside the <head> section. We have added the bootstrap class .container to the <div> element.

At last, at the bottom just before closing the </body> tag, we are referencing the home.js script file which is present in the static folder of src/main/resources

Run the app


Run the application using the below maven command –

mvn spring-boot:run

Open the browser and enter the following URL – http://localhost:8080/datetimeScreenshot-2021-04-12-at-4-52-22-PM



Partners: JackTop Casino online casino ohne registrierung online casino ohne bonus erfahrungen snai book of ra nya utländska casino med trustly online casino zahlungen mit neteller kasino astropay malaysia nordea uhkapelaamisen esto astropay online casinos bwin geld von sportwetten auf casino übertragen

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply