Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
H

htmx-spring-boot

> 后端框架
Open source

Spring Boot and Thymeleaf helpers for working with htmx

686 stars0 likes1 views
WebsiteGitHub

About

Spring Boot and Thymeleaf helpers for working with htmx

Spring Boot and Thymeleaf library for htmx

Want to write production-ready Spring Boot starters like this one? Read Crafting Spring Boot Starters.

The project simplifies the integration of htmx with Spring Boot / Spring Web MVC applications. It provides a set of views, annotations, and argument resolvers for controllers to easily handle htmx-related request and response headers. This ensures seamless interaction between the frontend and backend, especially for dynamic content updates via htmx.

Additionally, the project includes a custom Thymeleaf dialect to enable smooth rendering of htmx-specific attributes within Thymeleaf templates. With these tools, developers can quickly implement htmx-driven interactions, such as AJAX-based partial page updates, with minimal configuration.

Maven configuration

The project provides the following libraries, which are available on Maven Central, so it is easy to add the desired dependency to your project.

htmx-spring-boot

Provides annotations and helper classes.

xml

    io.github.wimdeblauwe
    htmx-spring-boot
    LATEST_VERSION_HERE

htmx-spring-boot-thymeleaf

Provides a Thymeleaf dialect to easily work with htmx attributes.

xml

    io.github.wimdeblauwe
    htmx-spring-boot-thymeleaf
    LATEST_VERSION_HERE

Usage

Configuration

The included Spring Boot Auto-configuration will enable the htmx integrations.

Mapping Requests

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.

java
@HxRequest
@GetMapping("/users")
public String users() {
    return "view";
}

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

java
@HxRequest("my-element")
@GetMapping("/users")
public String users() {
    return "view";
}

If you want to restrict the invocation of a controller method to having a specific target element defined, use HxRequest#target

java
@HxRequest(target = "my-target")
@GetMapping("/users")
public String users() {
    return "view";
}

Request Headers

To access the various htmx Request Headers in a controller method, you can use the class HtmxRequest as a controller method argument.

java
@HxRequest
@GetMapping("/users")
public String users(HtmxRequest htmxRequest) {
    if (htmxRequest.isHistoryRestoreRequest()) {
        // do something
    }
    return "view";
}

Response Headers

There are two ways to set htmx Response Headers in controller methods. The first is to use HtmxResponse as controller method argument in combination with different Views e.g. HtmxRedirectView as return value. The second is to use annotations, e.g. @HxTrigger to set the necessary response headers. The first method is more flexible and allows you to dynamically set the response headers based on the request.

HtmxResponse and Views

Most of the htmx Response Headers can be set by using HtmxResponse as controller method argument, except for some control flow response headers such as HX-Redirect. For these response headers, you have to use a corresponding view as return value of the controller method.

  • HtmxRedirectView - sets the HX-Redirect header to do a client-side redirect.
  • HtmxLocationRedirectView - sets the HX-Location header to do a client-side redirect without reloading the whole page.
  • HtmxRefreshView - sets the HX-Refresh header to do a client-side refresh of the current page.
Special view name prefixes

For these views, there is also a special view name handling if you prefer to return a view name instead of a view instance.

  • Redirect URLs can be specified via redirect:htmx:, e.g. redirect:htmx:/path, which causes htmx to perform a redirect to the specified URL.
  • Location redirect URLs can be specified via redirect:htmx:location:, e.g. redirect:htmx:location:/path, which causes htmx to perform a client-side redirect without reloading the entire page.
  • A refresh of the current page can be specified using refresh:htmx.
java
@HxRequest
@PostMapping("/user/{id}")
public String user(@PathVariable Long id, @ModelAttribute @Valid UserForm form, 
                 BindingResult bindingResult, RedirectAttributes redirectAttributes,
                 HtmxResponse htmxResponse) {

    if (bindingResult.hasErrors()) {
        return "user/form";
    }

    // update user ...
    redirectAttributes.addFlashAttribute("successMessage", "User has been successfully updated.");
    htmxResponse.addTrigger("user-updated");
    
    return "redirect:htmx:/user/list";
}

Annotations

The following annotations can be used on controller methods to set the necessary response headers.

  • @HxPushUrl
  • @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.

java
@HxRequest
@HxTrigger("userUpdated") // the event 'userUpdated' will be triggered by htmx
@GetMapping("/users")
public String users() {
    return "view";
}

HTML Fragments

In Spring MVC, view rendering typically involves specifying one view and one model. However, in htmx a common capability is to send multiple HTML fragments that htmx can use to update different parts of the page, which is called Out Of Band Swaps. Spring offers the ability to return multiple HTML fragments using Collection or FragmentsRendering as return type of controller. Further information on this can be found in the Spring Framework documentation under HTML Fragments.

java
@HxRequest
@GetMapping("/users")
public View users(Model model) {
    model.addAttribute("users", userRepository.findAll());
    model.addAttribute("count", userRepository.count());

    return FragmentsRendering
        .with("users/list")
        .fragment("users/count")
        .build();
}

Example with Collection:

java
@HxRequest
@GetMapping("/users")
public Collection users() {
    return List.of(
            new ModelAndView("users/list", Map.of("users", userRepository.findAll())),
            new ModelAndView("users/count", Map.of("count", userRepository.count()))
    );
}

Exceptions

It is also possible to use HtmxRequest and HtmxResponse as method argument in handler methods annotated with @ExceptionHandler.

java

@ExceptionHandler(Exception.class)
public String handleError(Exception ex, HtmxRequest htmxRequest, HtmxResponse htmxResponse) {
    if (htmxRequest.isHtmxRequest()) {
        htmxResponse.setRetarget("#error-message");
    }
    return "error";
}

It is also possible to add annotations on an exception handler to set response headers.

java
@ExceptionHandler(Exception.class)
@HxRetarget("#error-message")
public String handleError(Exception ex) {
    return "error";
}

Spring Security

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:

java
@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(configurer -> configurer.defaultAuthenticationEntryPointFor(entryPoint, requestMatcher));
    return http.build();
}

In addition, htmx provides a special way to send a redirect instruction to the client, keeping a success code ([200](https://developer.mozi

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Javahtmxspring-bootthymeleaf

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架