This project provides annotations, helper classes and a Thymeleaf dialect to make it easy to work with htmx in a Spring Boot application.
More information about htmx can be viewed on their website.
The project provides the following libraries, which are available on Maven Central, so it is easy to add the desired dependency to your project.
Provides annotations and helper classes.
<dependency>
<groupId>io.github.wimdeblauwe</groupId>
<artifactId>htmx-spring-boot</artifactId>
<version>LATEST_VERSION_HERE</version>
</dependency>
Provides a Thymeleaf dialect to easily work with htmx attributes.
<dependency>
<groupId>io.github.wimdeblauwe</groupId>
<artifactId>htmx-spring-boot-thymeleaf</artifactId>
<version>LATEST_VERSION_HERE</version>
</dependency>
The included Spring Boot Auto-configuration will enable the htmx integrations.
Controller methods can be annotated with
HxRequest
to be selected only if it is a htmx-based request (e.g. hx-get
).
This annotation allows composition if you want to combine them.
For example, you can combine annotations to create a custom @HxGetMapping
.
The following method is called only if the request was made by htmx.
@HxRequest
@GetMapping("/users")
public String htmxRequest(){
return "partial";
}
In addition, if you want to restrict the invocation of a controller method to a specific triggering element, you can set HxRequest#value to the ID or name of the element. If you want to be explicit use HxRequest#triggerId or HxRequest#triggerName
@HxRequest("my-element")
@GetMapping("/users")
public String htmxRequest(){
return "partial";
}
If you want to restrict the invocation of a controller method to having a specific target element defined, use HxRequest#target
@HxRequest(target = "my-target")
@GetMapping("/users")
public String htmxRequest(){
return "partial";
}
The HtmxRequest object can be used as controller method parameter to access the various htmx Request Headers.
@HxRequest
@GetMapping("/users")
public String htmxRequest(HtmxRequest htmxRequest) {
if(htmxRequest.isHistoryRestoreRequest()){
// do something
}
return "partial";
}
There are two ways to set htmx Response Headers on controller methods.
The first is to use annotations, e.g. @HxTrigger
, and the second is to use the class HtmxResponse as the return type of the controller method.
See Response Headers Reference for the related htmx documentation.
The following annotations are currently supported:
- @HxLocation
- @HxPushUrl
- @HxRedirect
- @HxRefresh
- @HxReplaceUrl
- @HxReselect
- @HxReswap
- @HxRetarget
- @HxTrigger
- @HxTriggerAfterSettle
- @HxTriggerAfterSwap
Note Please refer to the related Javadoc to learn more about the available options.
If you want htmx to trigger an event after the response is processed, you can use the annotation @HxTrigger
which sets the necessary response header HX-Trigger.
@HxRequest
@HxTrigger("userUpdated") // the event 'userUpdated' will be triggered by htmx
@GetMapping("/users")
public String hxUpdateUser(){
return "partial";
}
If you want to do the same, but in a more flexible way, you can use HtmxResponse
as the return type in the controller method instead.
@HxRequest
@GetMapping("/users")
public HtmxResponse hxUpdateUser(){
return HtmxResponse.builder()
.trigger("userUpdated") // the event 'userUpdated' will be triggered by htmx
.view("partial")
.build();
}
htmx supports updating multiple targets by returning multiple partials in a single response, which is called Out Of Band Swaps. For this purpose, use HtmxResponse as the return type of a controller method, where you can add multiple templates.
@HxRequest
@GetMapping("/partials/main-and-partial")
public HtmxResponse getMainAndPartial(Model model){
model.addAttribute("userCount", 5);
return HtmxResponse.builder()
.view("users-list")
.view("users-count")
.build();
}
An HtmxResponse
can be formed from view names, as above, or fully resolved View
instances, if the controller knows how
to do that, or from ModelAndView
instances (resolved or unresolved). For example:
@HxRequest
@GetMapping("/partials/main-and-partial")
public HtmxResponse getMainAndPartial(Model model){
return HtmxResponse.builder()
.view(new ModelAndView("users-list")
.view(new ModelAndView("users-count", Map.of("userCount",5))
.build();
}
Using ModelAndView
means that each fragment can have its own model (which is merged with the controller model before rendering).
An HtmxReponse.Builder
can be injected as a controller method. This creates the parameter and adds it to the model,
allowing it to be used without requiring it be the method return value. This is useful when the return value is needed for
the template.
This allows for the following usage:
@GetMapping("/endpoint")
public String endpoint(HtmxResponse.Builder htmxResponse, Model model) {
htmxResponse.trigger("event1");
model.addAttribute("aField", "aValue");
return "endpointTemplate";
}
For example the JTE templating library supports statically typed templates and can be used like so:
@GetMapping("/endpoint")
public JteModel endpoint(HtmxResponse.Builder htmxResponse) {
htmxResponse.trigger("event1");
String aField = "aValue";
return templates.endpointTemplate(aField);
}
It is possible to use HtmxResponse
as a return type from error handlers.
This makes it quite easy to declare a global error handler that will show a message somewhere whenever there is an error
by declaring a global error handler like this:
@ExceptionHandler(Exception.class)
public HtmxResponse handleError(Exception ex) {
return HtmxResponse.builder()
.reswap(HtmxReswap.none())
.view(new ModelAndView("fragments :: error-message", Map.of("message", ex.getMessage())))
.build();
}
This will override the normal swapping behaviour of any htmx request that has an exception to avoid swapping to occur.
If the error-message
fragment is declared as an Out Of Band Swap and your page layout has an empty div to "receive"
that piece of HTML, then only that will be placed on the screen.
The library has an HxRefreshHeaderAuthenticationEntryPoint
that you can use to have htmx force a full page browser
refresh in case there is an authentication failure.
If you don't use this, then your login page might be appearing in place of a swap you want to do somewhere.
See htmx-authentication-error-handling
blog post for detailed information.
To use it, add it to your security configuration like this:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http)throws Exception{
// probably some other configurations here
var entryPoint = new HxRefreshHeaderAuthenticationEntryPoint();
var requestMatcher = new RequestHeaderRequestMatcher("HX-Request");
http.exceptionHandling(exception ->
exception.defaultAuthenticationEntryPointFor(entryPoint, requestMatcher));
return http.build();
}
The Thymeleaf integration for Spring supports the specification of a Markup Selector for views. The Markup Selector will be used for selecting the section of the template that should be processed, discarding the rest of the template. This is quite handy when it comes to htmx and for example Out Of Band Swaps, where you only have to return parts of your template.
The following example combines two partials via HtmxResponse
with a Markup Selector
that selects the fragment list
(th:fragment="list"
) and another that selects the
fragment count
(th:fragment="count") from the template users
.
@HxRequest
@GetMapping("/partials/main-and-partial")
public HtmxResponse getMainAndPartial(Model model){
model.addAttribute("userCount", 5);
return HtmxResponse.builder()
.view("users :: list")
.view("users :: count")
.build();
}
The Thymeleaf dialect has appropriate processors that enable Thymeleaf to perform calculations and expressions in htmx-related attributes.
See Attribute Reference for the related htmx documentation.
Note The
:
colon instead of the typical hyphen.
hx:get
: This is a Thymeleaf processing enabled attributehx-get
: This is just a static attribute if you don't need the Thymeleaf processing
For example, this Thymeleaf template:
<div hx:get="@{/users/{id}(id=${userId})}" hx-target="#otherElement">Load user details</div>
Will be rendered as:
<div hx-get="/users/123" hx-target="#otherElement">Load user details</div>
The Thymeleaf dialect has corresponding processors for most of the hx-*
attributes.
Please open an issue if something is missing.
Note Be careful about using
#
in the value. If you dohx:target="#mydiv"
, then this will not work as Thymeleaf uses the#
symbol for translation keys. Either usehx-target="#mydiv"
orhx:target="${'#mydiv'}"
The hx-vals attribute allows to add to the parameters that will be submitted with the AJAX request. The value of the attribute should be a JSON string.
The library makes it a bit easier to write such a JSON string by adding support for inline maps.
For example, this Thymeleaf expression:
<div hx:vals="${ {id: user.id } }"></div>
will render as:
<div hx-vals="{&quot;id&quot;: 1234 }"></div>
(Given user.id
has the value 1234
)
You can use multiple values like this:
<div hx:vals="${ {id: user.id, groupId: group.id } }"></div>
Links to articles and blog posts about this library:
- Release 1.0.0 and 2.0.0 of htmx-spring-boot-thymeleaf
- Htmx authentication error handling
- Thymeleaf and htmx with out of band swaps
Library version | Spring Boot | Minimum Java version |
---|---|---|
3.5.1 | 3.2.x | 17 |
3.4.1 | 3.2.x | 17 |
3.3.0 | 3.1.x | 17 |
3.2.0 | 3.1.x | 17 |
2.2.0 | 3.0.x | 17 |
1.0.0 | 2.7.x | 11 |
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
To release a new version of the project, follow these steps:
- Update
pom.xml
with the new version (Usemvn versions:set -DgenerateBackupPoms=false -DnewVersion=<VERSION>
) - Commit the changes locally.
- Tag the commit with the version (e.g.
1.0.0
) and push the tag. - Create a new release in GitHub via https://github.com/wimdeblauwe/htmx-spring-boot/releases/new
- Select the newly pushed tag
- Update the release notes. This should automatically start the release action.
- Update
pom.xml
again with the nextSNAPSHOT
version. - Close the milestone in the GitHub issue tracker.