GSP Without Grails: Groovy Server Pages as the View Layer of a Spring Boot 4 App

Estimated reading time: ~25 minutes. All the code, including a Thymeleaf version of the same app for comparison, is in the companion repository.
In this tutorial we build a small Spring Boot web application whose views are written in Groovy Server Pages instead of Thymeleaf, and the languages and frameworks used are Spring Boot 4.1, Grails 8 GSP (8.0.0-RC1), Groovy 5 and Java 21, with Spring Data JPA and H2 underneath. There’s no Grails application here. The controllers are ordinary Spring MVC controllers written in Java, and GSP is the view technology they hand their models to.

You should be comfortable with Spring Boot, Spring MVC and Gradle. You don’t need to know Grails, and you only need a little Groovy: the controllers and entities stay in Java, and Groovy appears in the pages and in one tag library class. If you’ve built server-rendered views with Thymeleaf before, as we did in the Spring Boot CRM tutorial and the HTMX and Thymeleaf guide, you’ll recognise the shape of everything here. And if you’ve used GSP in a Grails app, such as in our simple CRM with Grails 4, the pages themselves will look very familiar.
The app is a quest board for the Knights of the Round Table: a list of quests with a status and a peril rating, a page per quest, and a form to post a new one. Here’s the finished board:

GSP has been the view layer of Grails since the beginning, and the Grails source tree carries an example of it running inside a plain Spring Boot app. On the 8.x line that example couldn’t start until a pull request merged on 16 September 2026 (apache/grails-core#16184), which describes the first failure and four more behind it. With that fix in, a plain SpringApplication can render its views with GSP without the Grails plugin lifecycle, and the RC1 guide documents it as “GSP in a Spring Boot Application”. The Grails code calls this standalone mode, and so will I. Spring MVC keeps the routing and binding, and GSP handles the HTML.
Everything here was built and run against Grails 8.0.0-RC1 and Spring Boot 4.1.1. RC1 is a release candidate, so a version or two may move before 8.0.0 is final, and I’ll point out the places that were rough on RC1 as we go.
Why use GSP in a Spring Boot app
Thymeleaf is the default for server-side views in Spring Boot, and for good reason: it’s on Spring Initializr, it has a Boot starter, and its templates are valid HTML that open in a browser as they are. So it’s fair to ask why you’d swap it out.
Custom tags are where GSP pulls ahead. In GSP a tag is a method on a Groovy class that writes to out. In Thymeleaf the equivalent is a dialect class plus a processor class per tag, built against Thymeleaf’s model API. For this tutorial I wrote the same two tags both ways: 27 lines of one Groovy class in GSP, and 84 lines across three Java classes in Thymeleaf. Some of that gap is Groovy being terser than Java, and some is the processor API itself.
GSP expressions are Groovy, so a page can group, count, filter and use safe navigation with the same syntax you’d use in code. Thymeleaf gives you SpEL inside attributes, with its own selection and projection syntax and a set of utility objects for formatting. Neither is hard to learn; Groovy just has the advantage of being a general-purpose language you may already use elsewhere.
Layouts in GSP work by decoration. A GSP page is a complete HTML document with its own head and body, and SiteMesh wraps it in a layout afterwards. Thymeleaf doesn’t have layout decoration built in, so you either include fragments into every page or add the third-party Layout Dialect, which is what the comparison app uses.
GSP pages are also compiled into classes at build time, so a syntax error in a template fails the Gradle build. The guarantee is narrower than it sounds, and we’ll test exactly what it catches later on.
There are costs too. GSP brings more dependencies: on my machine (details in the comparison section) the GSP version of this app packages to a 73.0 MB jar with 120 libraries, against 65.1 MB and 82 for the Thymeleaf version, and it starts in about 6.2 seconds against 4.8. Thymeleaf’s form binding is built in, where standalone GSP needs a small tag for field errors. And in standalone mode only a handful of GSP’s built-in tags are switched on, which gets its own section. How much the trade is worth depends on how much logic your views carry.
Setting up the project
Start with Spring Initializr, either at start.spring.io or through your IDE. As usual I’m using IntelliJ IDEA. Choose a Gradle – Groovy project, Spring Boot 4.1.1 and Java 21 (Grails 8 needs Java 21 as a minimum), with group com.tucanoo, artifact gsp-app and package name com.tucanoo.questboard. Add Spring Web, Spring Data JPA, H2 Database and Validation. There’s no GSP entry on Initializr, so the GSP parts are added by hand next.
Initializr names the main class after the artifact, so rename it to QuestBoardApplication. It’s the standard Boot entry point:
package com.tucanoo.questboard;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class QuestBoardApplication {
public static void main(String[] args) {
SpringApplication.run(QuestBoardApplication.class, args);
}
}Next, replace build.gradle with the following:
plugins {
id 'java'
id 'groovy'
id 'org.springframework.boot' version '4.1.1'
id 'org.apache.grails.gradle.grails-gsp' version '8.0.0-RC1'
id 'cloud.wondrify.asset-pipeline' version '5.2.0-RC1'
}
group = 'com.tucanoo'
version = '0.0.1-SNAPSHOT'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation platform('org.apache.grails:grails-bom:8.0.0-RC1')
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-validation'
runtimeOnly 'com.h2database:h2'
// The RC1 guide prints org.apache.grails.views here, which does not exist on Maven Central
implementation 'org.apache.grails:grails-gsp-spring-boot'
implementation 'cloud.wondrify:asset-pipeline-spring-boot'
implementation 'cloud.wondrify:asset-pipeline-gsp'
assetDevelopmentRuntime platform('org.apache.grails:grails-bom:8.0.0-RC1')
assetDevelopmentRuntime 'org.webjars.npm:bootstrap'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
assets {
assetsPath = file('src/main/assets')
excludeWebjarsByDefault = true
enableSourceMaps = false
developmentRuntime = false
}
compileGroovyPages {
source = file('src/main/resources/templates')
serverpath = '/'
}
tasks.named('test') {
useJUnitPlatform()
}Most of this is a normal Boot build. The Grails parts are:
- the
groovyplugin, because the build compiles Groovy pages and our tag library; - the
org.apache.grails.gradle.grails-gspplugin, which adds thecompileGroovyPagestask that turns each page into a class; - the Grails BOM, which manages the versions of everything Grails-related, including the GSP Spring Boot module;
org.apache.grails:grails-gsp-spring-boot, which auto-configures the template engine, the view resolver, the tag libraries and SiteMesh;- the asset pipeline plugin and its two modules, which we’ll cover in the styling section.
The compileGroovyPages block tells the task where the templates live and what path to register them under. The serverpath = '/' line matters: by default the task registers pages below /WEB-INF/grails-app/views/, which is where a Grails application looks for them. A Spring Boot app asks for /quests/board.gsp, so the registered path must have no prefix, and without this line the compiled pages are never found.
If you copied the build snippet from the Grails guide
The RC1 guide’s section on GSP in Spring Boot shows a short build snippet, and it doesn’t build as printed. If you’re here because of one of these errors, this is the fix. Copied exactly, the snippet applies neither the java nor the groovy plugin, and the first error is:
Could not find method implementation() for arguments [org.apache.grails:grails-bom:8.0.0-RC1]Adding id 'java' moves you on to:
Could not find method compileGroovyPages() for arguments [...] on root projectwhich id 'groovy' fixes. The last one is the dependency itself. The guide gives it as org.apache.grails.views:grails-gsp-spring-boot, but there’s nothing on Maven Central under that group, so you get:
Could not find org.apache.grails.views:grails-gsp-spring-boot:.The artifact is published as org.apache.grails:grails-gsp-spring-boot, and the BOM supplies its version, which is what the build file above uses.
Application properties
Next, src/main/resources/application.properties:
spring.application.name=quest-board
spring.datasource.url=jdbc:h2:mem:camelot
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.open-in-view=false
sitemesh.decorator.default=mainThe only GSP-specific line is the last one, which names the layout every page is decorated with unless it asks for another. The rest sets up an in-memory H2 database called camelot. You can delete the generated HELP.md if you like; nothing else from Initializr needs changing.
The quest data
The domain is deliberately small: knights, and the quests they’ve signed up for. Under com.tucanoo.questboard.domain, create a QuestStatus enum:
package com.tucanoo.questboard.domain;
public enum QuestStatus {
PROPOSED,
UNDER_WAY,
ACHIEVED,
RAN_AWAY
}Then a Knight entity. There’s no Lombok in this project, so the getters and setters are written out:
package com.tucanoo.questboard.domain;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Knight {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String epithet;
private String favouriteColour;
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEpithet() {
return epithet;
}
public void setEpithet(String epithet) {
this.epithet = epithet;
}
public String getFavouriteColour() {
return favouriteColour;
}
public void setFavouriteColour(String favouriteColour) {
this.favouriteColour = favouriteColour;
}
}And the Quest entity, which carries the validation rules the form will use later. Peril runs from 1 to 5, and a quest doesn’t need a knight:
package com.tucanoo.questboard.domain;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
@Entity
public class Quest {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Size(max = 80)
private String title;
@Size(max = 500)
private String description;
@NotNull
@Enumerated(EnumType.STRING)
private QuestStatus status = QuestStatus.PROPOSED;
@NotNull
@Min(1)
@Max(5)
private Integer peril;
@ManyToOne
private Knight knight;
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public QuestStatus getStatus() {
return status;
}
public void setStatus(QuestStatus status) {
this.status = status;
}
public Integer getPeril() {
return peril;
}
public void setPeril(Integer peril) {
this.peril = peril;
}
public Knight getKnight() {
return knight;
}
public void setKnight(Knight knight) {
this.knight = knight;
}
}Two Spring Data repositories in the same package complete the data layer:
package com.tucanoo.questboard.domain;
import org.springframework.data.jpa.repository.JpaRepository;
public interface KnightRepository extends JpaRepository<Knight, Long> {
}package com.tucanoo.questboard.domain;
import org.springframework.data.jpa.repository.JpaRepository;
public interface QuestRepository extends JpaRepository<Quest, Long> {
}For the sample data, Hibernate runs any import.sql it finds on the class path when it creates the schema, so put the following in src/main/resources/import.sql:
INSERT INTO knight (name, epithet, favourite_colour) VALUES ('Arthur', 'King of the Britons', 'Blue');
INSERT INTO knight (name, epithet, favourite_colour) VALUES ('Sir Lancelot', 'the Brave', 'Blue');
INSERT INTO knight (name, epithet, favourite_colour) VALUES ('Sir Galahad', 'the Pure', 'Blue. No, yellow');
INSERT INTO knight (name, epithet, favourite_colour) VALUES ('Sir Robin', 'the Not-Quite-So-Brave-as-Sir-Lancelot', 'Unknown');
INSERT INTO knight (name, epithet, favourite_colour) VALUES ('Sir Bedevere', 'the Wise', 'Green');
INSERT INTO knight (name, epithet, favourite_colour) VALUES ('Patsy', 'Keeper of the Coconuts', 'Brown');
INSERT INTO quest (title, description, status, peril, knight_id) VALUES ('Seek the Holy Grail', 'The Lady of the Lake was quite specific about this one.', 'UNDER_WAY', 5, 1);
INSERT INTO quest (title, description, status, peril, knight_id) VALUES ('Fetch one shrubbery', 'One that looks nice. And not too expensive.', 'ACHIEVED', 2, 1);
INSERT INTO quest (title, description, status, peril, knight_id) VALUES ('Cross the Bridge of Death', 'Answer me these questions three.', 'PROPOSED', 4, 4);
INSERT INTO quest (title, description, status, peril, knight_id) VALUES ('Defeat the Rabbit of Caerbannog', 'Count to three, no more, no less.', 'RAN_AWAY', 5, 1);
INSERT INTO quest (title, description, status, peril, knight_id) VALUES ('Rescue the maiden of Swamp Castle', 'Turned out to be a prince with a note.', 'ACHIEVED', 3, 2);
INSERT INTO quest (title, description, status, peril, knight_id) VALUES ('Leave Castle Anthrax', 'Possibly the hardest quest on the board.', 'ACHIEVED', 4, 3);
INSERT INTO quest (title, description, status, peril, knight_id) VALUES ('Face the Black Knight', 'Tis but a scratch.', 'ACHIEVED', 3, 1);
INSERT INTO quest (title, description, status, peril, knight_id) VALUES ('Establish the airspeed velocity of an unladen swallow', 'African or European?', 'PROPOSED', 1, 5);
INSERT INTO quest (title, description, status, peril, knight_id) VALUES ('Build a large wooden rabbit', 'Remember to get inside it this time.', 'RAN_AWAY', 2, 5);
INSERT INTO quest (title, description, status, peril, knight_id) VALUES ('Find a herring', 'For cutting down the mightiest tree in the forest.', 'PROPOSED', 2, NULL);The IDs are generated by the database (GenerationType.IDENTITY), so the knights get 1 to 6 in the order they’re inserted, and the quests can refer to them by those numbers.
A controller that returns GSP views
Nothing about the controller is GSP-specific. Under com.tucanoo.questboard.web, create QuestController:
package com.tucanoo.questboard.web;
import com.tucanoo.questboard.domain.KnightRepository;
import com.tucanoo.questboard.domain.Quest;
import com.tucanoo.questboard.domain.QuestRepository;
import com.tucanoo.questboard.domain.QuestStatus;
import jakarta.validation.Valid;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.server.ResponseStatusException;
import static org.springframework.http.HttpStatus.NOT_FOUND;
@Controller
public class QuestController {
private final QuestRepository quests;
private final KnightRepository knights;
public QuestController(QuestRepository quests, KnightRepository knights) {
this.quests = quests;
this.knights = knights;
}
@GetMapping("/")
public String board(Model model) {
model.addAttribute("quests", quests.findAll(Sort.by("title")));
return "quests/board";
}
@GetMapping("/quests/{id}")
public String show(@PathVariable Long id, Model model) {
model.addAttribute("quest", quests.findById(id)
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND)));
return "quests/show";
}
@GetMapping("/quests/new")
public String create(Model model) {
model.addAttribute("quest", new Quest());
return form(model);
}
@PostMapping("/quests")
public String save(@Valid @ModelAttribute("quest") Quest quest, BindingResult result, Model model) {
if (result.hasErrors()) {
return form(model);
}
Quest saved = quests.save(quest);
return "redirect:/quests/" + saved.getId();
}
private String form(Model model) {
model.addAttribute("knights", knights.findAll(Sort.by("name")));
model.addAttribute("statuses", QuestStatus.values());
return "quests/form";
}
}Each handler returns a view name, and GSP’s view resolver maps it to a template: quests/board renders src/main/resources/templates/quests/board.gsp. If you later want the templates somewhere else, spring.gsp.templateRoots changes the location.
Two details here are easy to miss. The form posts the knight as an ID, and Spring Data’s web support, which Boot switches on automatically, converts that ID into a Knight without any binder code of our own. And an unknown quest ID throws ResponseStatusException, so /quests/999 gives a normal 404.
The diagram below shows where GSP sits once a handler returns. Spring MVC does the routing and binding as usual, and GSP takes over at the view.

The first page
Create src/main/resources/templates/quests/board.gsp:
<html>
<head>
<title>All quests</title>
</head>
<body>
<g:set var="byStatus" value="${quests.groupBy { it.status }}"/>
<p class="text-body-secondary">
${quests.size()} quests on the board, ${byStatus[com.tucanoo.questboard.domain.QuestStatus.ACHIEVED]?.size() ?: 0} achieved,
${quests.count { it.knight == null }} still looking for a knight.
</p>
<p class="small">Average peril: <g:formatNumber number="${quests*.peril.sum() / quests.size()}" format="0.0"/>.</p>
<div class="row g-3">
<g:each in="${quests}" var="quest">
<div class="col-md-6 col-lg-4">
<g:render template="/quests/questCard" model="[quest: quest]"/>
</div>
</g:each>
</div>
</body>
</html>The model attributes are available by name, so ${quests} is the list the controller added. Because expressions are Groovy, the summary line can do its own arithmetic: groupBy builds a map of quests per status, count takes a closure, and ?. with ?: copes with a status that has no quests. I’ve used the fully qualified enum name to keep the example self-contained; a <%@ page import="..." %> directive at the top of the page would shorten it.
<g:each> loops, and <g:render> renders a partial for each card. By convention a partial’s file name starts with an underscore, so the template="/quests/questCard" attribute refers to templates/quests/_questCard.gsp:
<div class="card h-100 shadow-sm">
<div class="card-body">
<div class="d-flex justify-content-between align-items-start mb-2">
<h2 class="h6 mb-0"><a href="/quests/${quest.id}">${quest.title}</a></h2>
<quest:status value="${quest.status}"/>
</div>
<p class="small text-body-secondary mb-2">${quest.knight?.name ?: 'Unassigned'}</p>
<quest:peril level="${quest.peril}"/>
</div>
</div>There are two things here we haven’t built yet. The <quest:status> and <quest:peril> tags come from our own tag library, and the <g:set> and <g:formatNumber> tags on the board page need a small piece of configuration in standalone mode. We’ll get to both shortly. First, the show page, templates/quests/show.gsp:
<html>
<head>
<title>${quest.title}</title>
</head>
<body>
<div class="card shadow-sm">
<div class="card-body">
<div class="d-flex justify-content-between align-items-start">
<h1 class="h4">${quest.title}</h1>
<quest:status value="${quest.status}"/>
</div>
<p>${quest.description}</p>
<g:if test="${quest.knight}">
<p class="mb-1">Undertaken by <strong>${quest.knight.name}</strong>, ${quest.knight.epithet}.</p>
<p class="small text-body-secondary">Favourite colour: ${quest.knight.favouriteColour}</p>
</g:if>
<g:else>
<p class="text-body-secondary">No knight has volunteered yet.</p>
</g:else>
<quest:peril level="${quest.peril}"/>
</div>
</div>
<g:applyLayout name="notice">
Quests marked "ran away" may be retried at any time. Bravely.
</g:applyLayout>
</body>
</html><g:if> and <g:else> are handled by the GSP compiler itself, so they work without any tag library. The <g:applyLayout> at the bottom is a SiteMesh feature, which brings us to layouts.
Layouts with SiteMesh
Notice that board.gsp and show.gsp are complete HTML documents, each with a <head> and a <title>. Neither says anything about the navigation bar or the stylesheets. SiteMesh decorates each page after it renders, and the decorator is the layout named by sitemesh.decorator.default=main. Layouts live in a layouts folder under the template root, so create templates/layouts/main.gsp:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title><g:layoutTitle default="Quest Board"/> | Camelot</title>
<asset:stylesheet src="application.css"/>
<g:layoutHead/>
</head>
<body class="bg-body-tertiary">
<nav class="navbar bg-dark border-bottom mb-4" data-bs-theme="dark">
<div class="container">
<a class="navbar-brand" href="/">Camelot Quest Board</a>
<a class="btn btn-outline-light btn-sm" href="/quests/new">Post a quest</a>
</div>
</nav>
<main class="container pb-5">
<g:layoutBody/>
</main>
<asset:javascript src="application.js"/>
</body>
</html><g:layoutTitle>, <g:layoutHead> and <g:layoutBody> pull the matching parts out of the page being decorated. Visiting /quests/1 therefore gives a page titled “Seek the Holy Grail | Camelot” with the navigation bar around it.
A layout can also decorate a fragment instead of a whole page. That’s what <g:applyLayout name="notice"> does at the bottom of the show page, using this small layout in templates/layouts/notice.gsp:
<div class="alert alert-light border mt-3 small mb-0">
<g:layoutBody/>
</div>For comparison, the Thymeleaf version of this app needs the Layout Dialect for the same effect: each page declares layout:decorate="~{layouts/main}" and wraps its content in a layout:fragment. It works well, but it’s an extra dependency and every page has to opt in.
Writing a tag library
This is the part I’d point a sceptical Thymeleaf user at first. Under src/main/groovy/com/tucanoo/questboard/taglib, create QuestTagLib.groovy:
package com.tucanoo.questboard.taglib
import com.tucanoo.questboard.domain.QuestStatus
import grails.gsp.TagLib
import org.springframework.stereotype.Component
import org.springframework.validation.BindingResult
@TagLib
@Component
class QuestTagLib {
static String namespace = 'quest'
private static final Map<QuestStatus, String> BADGES = [
(QuestStatus.PROPOSED) : 'text-bg-secondary',
(QuestStatus.UNDER_WAY): 'text-bg-primary',
(QuestStatus.ACHIEVED) : 'text-bg-success',
(QuestStatus.RAN_AWAY) : 'text-bg-warning'
]
def status(Map attrs) {
QuestStatus status = attrs.value as QuestStatus
String label = status.name().toLowerCase().replace('_', ' ').capitalize()
out << "<span class=\"badge ${BADGES[status]}\">${label}</span>"
}
def peril(Map attrs) {
int level = attrs.level as int
out << "<span class=\"peril\" title=\"Peril ${level} of 5\">"
5.times { i -> out << (i < level ? '<span class="pip on"></span>' : '<span class="pip"></span>') }
out << '</span>'
}
def fieldError(Map attrs) {
BindingResult result = request.getAttribute("${BindingResult.MODEL_KEY_PREFIX}${attrs.bean}") as BindingResult
result?.getFieldErrors(attrs.field as String)?.each {
out << "<div class=\"invalid-feedback d-block\">${it.defaultMessage}</div>"
}
}
}The namespace becomes the tag prefix, and each public method taking a Map of attributes becomes a tag. <quest:status value="${quest.status}"/> calls status with the enum in attrs.value, and the method writes a Bootstrap badge to out. peril draws five dots with a few filled in. fieldError we’ll use in the form section.
The RC1 guide registers a tag library with a @Bean method, and there’s a catch. If you put that method in a Java @Configuration class, the build fails with:
error: package com.tucanoo.questboard.taglib does not existGradle compiles src/main/java before src/main/groovy, so a Java configuration class can’t see a Groovy tag library. (The reverse is fine, which is why the tag library can use the Java QuestStatus enum.) The simplest way out is the one above: annotate the tag library with @Component as well as @TagLib and let component scanning register it. A @Bean method also works if the configuration class is written in Groovy, which is what we’ll do in the next section.
Here’s the Thymeleaf equivalent of the status tag from the comparison app. It needs a dialect class to register it, plus this processor:
package com.tucanoo.questboard.dialect;
import com.tucanoo.questboard.domain.QuestStatus;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.model.IModel;
import org.thymeleaf.model.IModelFactory;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractElementTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.standard.expression.StandardExpressions;
import org.thymeleaf.templatemode.TemplateMode;
import java.util.Map;
public class StatusTagProcessor extends AbstractElementTagProcessor {
private static final Map<QuestStatus, String> BADGES = Map.of(
QuestStatus.PROPOSED, "text-bg-secondary",
QuestStatus.UNDER_WAY, "text-bg-primary",
QuestStatus.ACHIEVED, "text-bg-success",
QuestStatus.RAN_AWAY, "text-bg-warning");
public StatusTagProcessor(String dialectPrefix) {
super(TemplateMode.HTML, dialectPrefix, "status", true, null, false, 1000);
}
@Override
protected void doProcess(ITemplateContext context, IProcessableElementTag tag,
IElementTagStructureHandler structureHandler) {
QuestStatus status = (QuestStatus) StandardExpressions.getExpressionParser(context.getConfiguration())
.parseExpression(context, tag.getAttributeValue("value"))
.execute(context);
String name = status.name().toLowerCase().replace('_', ' ');
String label = Character.toUpperCase(name.charAt(0)) + name.substring(1);
IModelFactory modelFactory = context.getModelFactory();
IModel model = modelFactory.createModel();
model.add(modelFactory.createOpenElementTag("span", "class", "badge " + BADGES.get(status)));
model.add(modelFactory.createText(label));
model.add(modelFactory.createCloseElementTag("span"));
structureHandler.replaceWith(model, false);
}
}It works and produces the same HTML, but you’re parsing the attribute expression yourself and building the output element by element through a model factory. The peril tag needs a second processor class of the same shape, and the dialect class registers both. That’s 84 non-blank lines against 27 for the same two tags in GSP, and to be fair to Thymeleaf, part of that is Java’s imports, casts and constructors. The GSP class has 33 non-blank lines in total, because it also holds fieldError, which Thymeleaf doesn’t need. For anything that’s mainly markup, Thymeleaf’s parameterised fragments are the more natural tool, and they’re shorter than a dialect.
Bringing back the g: tags you need
If you’ve used GSP in Grails, you’ll expect <g:set>, <g:formatNumber>, <g:link>, <g:message> and the form tags to be there. In standalone mode on RC1, most of them aren’t. Without any extra configuration the board page fails with:
Tag [set] does not exist. No tag library found for namespace: gThe auto-configuration registers three tag libraries: the render tags (g:render), the SiteMesh render tags, and the layout tags (g:layoutTitle, g:layoutHead, g:layoutBody, g:applyLayout). g:if, g:else and g:each are handled by the compiler. Everything else, from ApplicationTagLib to FormatTagLib and FormTagLib, is present in the jars but not registered.
You can register the ones you need as beans. Under src/main/groovy/com/tucanoo/questboard/config, create GrailsTagLibConfig.groovy:
package com.tucanoo.questboard.config
import org.grails.plugins.web.taglib.ApplicationTagLib
import org.grails.plugins.web.taglib.FormatTagLib
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class GrailsTagLibConfig {
@Bean
ApplicationTagLib applicationTagLib() {
new ApplicationTagLib()
}
@Bean
FormatTagLib formatTagLib() {
new FormatTagLib()
}
}With those two declared, <g:set> and <g:formatNumber> work, and the board shows an average peril of 3.1. I’d only register what you’ve tested, though. The guide warns that a tag library written for Grails may expect collaborators a Grails application would provide, and some tags in these classes depend on Grails services that standalone mode doesn’t set up.
Forms and validation
The form uses plain HTML inputs, bound and validated by Spring MVC in the usual way. Create templates/quests/form.gsp:
<html>
<head>
<title>Post a quest</title>
</head>
<body>
<h1 class="h4 mb-3">Post a quest</h1>
<form method="post" action="/quests" class="card card-body shadow-sm">
<div class="mb-3">
<label for="title" class="form-label">Title</label>
<input id="title" name="title" class="form-control" value="${quest.title}"/>
<quest:fieldError bean="quest" field="title"/>
</div>
<div class="mb-3">
<label for="description" class="form-label">Description</label>
<textarea id="description" name="description" class="form-control" rows="3">${quest.description}</textarea>
<quest:fieldError bean="quest" field="description"/>
</div>
<div class="row">
<div class="col-md-4 mb-3">
<label for="peril" class="form-label">Peril (1 to 5)</label>
<input id="peril" name="peril" type="number" min="1" max="5" class="form-control" value="${quest.peril}"/>
<quest:fieldError bean="quest" field="peril"/>
</div>
<div class="col-md-4 mb-3">
<label for="status" class="form-label">Status</label>
<select id="status" name="status" class="form-select">
<g:each in="${statuses}" var="s">
<option value="${s}" ${s == quest.status ? 'selected' : ''}>${s}</option>
</g:each>
</select>
</div>
<div class="col-md-4 mb-3">
<label for="knight" class="form-label">Knight</label>
<select id="knight" name="knight" class="form-select">
<option value="">Nobody yet</option>
<g:each in="${knights}" var="k">
<option value="${k.id}" ${k.id == quest.knight?.id ? 'selected' : ''}>${k.name}</option>
</g:each>
</select>
</div>
</div>
<div>
<button type="submit" class="btn btn-primary">Post quest</button>
</div>
</form>
</body>
</html>When @Valid fails, the controller renders the form again and Spring puts the BindingResult in the request under org.springframework.validation.BindingResult.quest. Our fieldError tag reads it from there and writes one message per error, so posting an empty title with a peril of 9 shows “must not be blank” and “must be less than or equal to 5” under the right fields. A valid post redirects to the new quest’s page.
This is the one area where Thymeleaf is clearly ahead. Its Spring integration gives you th:field and #fields.errors out of the box, so the Thymeleaf form needs no custom tag at all. In GSP you can also use Spring’s own form: JSP tags inside a page, as the official Grails example does, but that brings JSP support into the app, and I preferred one small tag.
Styling with the asset pipeline
The layout links its CSS and JavaScript with <asset:stylesheet> and <asset:javascript>. These come from the asset pipeline, which is how Grails applications have handled static resources for years, and it works in a plain Boot app too. Three parts of the build file set it up. The cloud.wondrify.asset-pipeline Gradle plugin compiles the assets at build time. asset-pipeline-spring-boot serves the compiled files, and asset-pipeline-gsp provides the asset: tags. As the guide notes, the pipeline builds asset URLs with a Grails link generator, so if you trim the Grails web dependencies, keep grails-web-url-mappings on the class path.
Bootstrap goes on the assetDevelopmentRuntime configuration, so it’s an input to the asset build and not packaged in the jar. The manifests in src/main/assets pull it in. stylesheets/application.css:
/*
*= require webjars/bootstrap/%/dist/css/bootstrap.css
*= require_self
*/
.peril { display: inline-flex; gap: 3px; }
.peril .pip { width: 10px; height: 10px; border-radius: 50%; background: #dee2e6; }
.peril .pip.on { background: #dc3545; }and javascripts/application.js:
//= require webjars/bootstrap/%/dist/js/bootstrap.bundle.jsThe % stands in for the webjar’s version, so the manifest doesn’t need editing when the BOM moves Bootstrap on. At build time the pipeline compiles each manifest into a single file with a content digest in its name, and the tags write that name into the page, for example /assets/application-230fe93500c1c4a5da3778dd0eb6f8cb.css.
One production caveat on RC1. The pipeline answers the logical URL /assets/application.css with Cache-Control: public, max-age=31536000, the same one-year header it gives the digest-named file. I measured that against the packaged app, and it’s listed as a known limitation in the pull request that made standalone GSP work. The digest file is safe to cache for a year because its name changes when its content does. The logical name doesn’t change, so anything that links to it directly can keep serving a stale stylesheet after a deploy. Linking through the tags, as the layout does, avoids that.
Compiled pages and templates on disk
compileGroovyPages turns every template into a class and writes a registry of them, gsp/views.properties, into the jar. But by default spring.gsp.templateRoots prefers the file system: if ./src/main/resources/templates exists relative to the working directory, GSP renders the templates themselves and ignores the compiled classes.
For development that’s useful. Run the app with ./gradlew bootRun, edit a page, refresh, and you’ll see the change without a restart. I tested it with the packaged jar too: started from inside the project directory, it picked up an edit to show.gsp on the next request. Started from any other directory, the same jar served the compiled page and ignored the edit. So you won’t exercise the compiled pages until the app runs somewhere without the source tree.
To see what compiling at build time catches, I tried three mistakes. A Groovy syntax error in an expression, ${quest.description.}, failed the build:
Unexpected input: '(' @ line 28, column 14.
...
Execution failed for task ':compileGroovyPages'.A misspelt property, ${quest.descripshun}, compiled without complaint, because GSP expressions are resolved at runtime. And a tag that doesn’t exist, such as <g:set> before we registered ApplicationTagLib, also compiled and only failed when the page rendered. The build catches syntax errors, which Thymeleaf only reports at render time; the other two need tests that render the pages.
Those tests should render the compiled pages. Gradle runs tests from the project directory, so by default they’d render the templates on disk, and pointing the template root at the class path fixes that. Here’s the test class from src/test/java/com/tucanoo/questboard:
package com.tucanoo.questboard;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import static org.assertj.core.api.Assertions.assertThat;
// Running from the project directory, GSP would render the templates in src/main/resources/templates.
// Pointing the template root at the class path makes these tests render the compiled pages, as the jar does.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = "spring.gsp.templateRoots=classpath:/templates")
class QuestBoardApplicationTests {
@Value("${local.server.port}")
int port;
private final HttpClient http = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NEVER)
.build();
@Test
void boardIsDecoratedWithTheMainLayout() throws Exception {
HttpResponse<String> response = get("/");
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.body())
.contains("<title>All quests | Camelot</title>")
.contains("Camelot Quest Board")
.contains("Seek the Holy Grail");
}
@Test
void questTagsRenderStatusAndPeril() throws Exception {
String body = get("/quests/1").body();
assertThat(body).contains("<span class=\"badge text-bg-primary\">Under way</span>");
assertThat(body.split("class=\"pip on\"", -1)).hasSize(6);
}
@Test
void invalidQuestIsSentBackWithErrors() throws Exception {
HttpResponse<String> response = post("title=&peril=9&status=PROPOSED&knight=");
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.body())
.contains("must not be blank")
.contains("must be less than or equal to 5");
}
@Test
void validQuestRedirectsToItsPage() throws Exception {
HttpResponse<String> response = post("title=Find+a+second+shrubbery&peril=2&status=PROPOSED&knight=6");
assertThat(response.statusCode()).isEqualTo(302);
assertThat(response.headers().firstValue("Location")).hasValueSatisfying(
location -> assertThat(location).matches(".*/quests/\\d+"));
}
@Test
void unknownQuestIsNotFound() throws Exception {
assertThat(get("/quests/999").statusCode()).isEqualTo(404);
}
private HttpResponse<String> get(String path) throws Exception {
return http.send(HttpRequest.newBuilder(uri(path)).build(), HttpResponse.BodyHandlers.ofString());
}
private HttpResponse<String> post(String form) throws Exception {
HttpRequest request = HttpRequest.newBuilder(uri("/quests"))
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString(form))
.build();
return http.send(request, HttpResponse.BodyHandlers.ofString());
}
private URI uri(String path) {
return URI.create("http://localhost:" + port + path);
}
}These run against a real port, so the SiteMesh decoration and the asset tags are part of what’s tested. ./gradlew test runs all five green. The Thymeleaf version of the app runs the same five tests, minus the template root property, and they pass there too, so both apps meet the same checks.
GSP and Thymeleaf side by side
Here’s how the two versions of the quest board compare, with a column for a full Grails 8 application for reference. The measured figures come from one machine (Intel Core i9-9900K, Windows 10, Amazon Corretto 21.0.7) with Spring Boot 4.1.1, with startup as the median of five runs. The line counts and jar sizes are exact; for startup, the ratio between the columns matters more than the seconds.
| GSP in Spring Boot | Thymeleaf | Full Grails 8 | |
|---|---|---|---|
| Custom tag (two tags, non-blank lines) | 27, one Groovy class | 84, a dialect and two processors | Same as GSP, registered by convention |
| Expressions | Groovy | SpEL with Thymeleaf utilities | Groovy |
| Layouts | SiteMesh decoration | Layout Dialect (third party) or fragments | SiteMesh decoration |
| Form binding and errors | Spring MVC, plus a small custom tag | Built in (th:field, #fields.errors) | Grails data binding, g:hasErrors, form tags |
| Standard tags available | Render and layout tags; others by bean | Full standard dialect | Full g: tag set |
| Template syntax errors | Fail the build | Reported at first render | Not tested here |
| Templates open in a browser as plain HTML | No | Yes | No |
| Project generator | Initializr, then manual setup | Initializr | Grails Forge (start.grails.org) |
| Executable jar | 73.0 MB, 120 libraries | 65.1 MB, 82 libraries | Not measured |
| Startup (median of 5) | 6.24 s | 4.80 s | Not measured |

The 7.9 MB difference includes Groovy itself (an 8.2 MB jar) and the persistence classes that grails-core still brings in, which the pull request puts at about 2.6 MB and describes as structural, partly offset by the Thymeleaf jars the GSP version doesn’t need. The official Grails example trims unused modules with Gradle exclude rules; its four Grails-module exclusions saved 1.2 MB here with all the tests still passing. The 1.4-second startup difference comes on top of an app that takes nearly five seconds to start in either version.
The first page view after startup took a median 0.91 seconds with GSP against 1.35 with Thymeleaf, which fits GSP serving precompiled classes while Thymeleaf parses its templates on first use. That’s a single cold request per run, and it says nothing about steady-state rendering speed.
If the views are mostly markup with a little data, I’d pick Thymeleaf in a Spring Boot app, for the easier setup and better tooling. If you have existing GSP views to keep, or pages that lean on custom tags and real logic, GSP is now a reasonable option inside Spring Boot.
What the full framework adds
Everything in this tutorial is the Grails view layer running on its own. Several of the rough edges above are things the rest of the framework would normally handle. In a Grails 8 application the full g: tag set is registered for you, so g:link generates URLs from your controllers and actions through URL mappings, and g:form, g:hasErrors and g:message work with Grails data binding and i18n. Tag libraries in grails-app/taglib are picked up by convention, with no annotation or bean method. Controllers, GORM for persistence and scaffolding follow the same conventions.
That’s a different trade from adding GSP to a Boot app, and it isn’t the right one for every project. If you’ve enjoyed the view side and want to see the rest, our posts on what’s coming in Grails 8 and Grails 7 cover where the framework is now.
Final thoughts
You should now have a working, if simplified, Spring Boot app rendering its views with GSP. It has a SiteMesh layout, a partial, a Groovy tag library, Spring MVC validation and Bootstrap compiled by the asset pipeline, and it’s tested against the compiled pages. To be clear about what we simplified: the database is in memory and reseeded on every start, there’s no security, the form is the only write path, and we’re on a release candidate whose rough edges (the guide’s build snippet, the reduced tag set, the asset cache header) may well be fixed by 8.0.0.
If you want to take it further, here are some exercises:
- Spring Security. Add a login and protect the form, then work out how you want the CSRF token into a GSP form. A small tag is one option.
- Messages and i18n. Register
ValidationTagLiband see how much ofg:messageworks against Spring’sMessageSourcein standalone mode. - HTMX partials. Have a controller return just
_questCard.gspfor an HTMX request and swap cards in place, as we did with Thymeleaf fragments in the HTMX guide. - Bring your own views. If you have a Grails app, copy a few of its views and tag libraries into a Boot app like this one and see which
g:tags you’d need to register.
Don’t forget all the code is available on GitHub, including the Thymeleaf version used for the comparison. If you’re moving to the Spring Boot 4 line generally, our migration guide covers that jump. I hope this has shown that GSP is now a view technology you can choose for a Spring Boot app, and that its tag libraries make it worth a look if your pages carry real logic.
