Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Spring Boot
  • Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
  • A Plain Spring Project, No Boot: Your First Bean With spring-context
  • Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
  • Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
  • Spring Autowiring: Spring Fills the Constructor, and When @Autowired Is Needed
  • Two Beans, One Type: Spring @Primary and @Qualifier
  • Spring Bean Scopes: Singleton vs Prototype, One Shared Object or a Fresh One
  • Spring Stereotypes: @Service, @Repository and @Controller Are @Component With a Job Name
  • The Spring Bean Lifecycle: @PostConstruct and @PreDestroy
  • The Mini Blog Wired by Spring: Plain Java vs Spring, Side by Side
  • Spring MVC and SQLite Without Spring Boot: the Mini Blog in the Browser
  • Your First Spring Boot 4 Project: Create It in IntelliJ, Run It, and the Four Files That Matter
  • What Is Spring Boot? Spring Framework 7 With the Decisions Already Made
  • The Project Context File: AGENTS.md and CLAUDE.md for a Spring Boot Project
  • Plan Before Code: a Five-Part Brief, Plan Mode and /goal for a Spring Boot Feature
  • From Design Frames to Thymeleaf Pages: Briefing an AI Agent for a Spring Boot Blog
  • Add, Edit and Delete Posts With a Rich-Text Editor in Spring Boot: Quill, jsoup and th:utext
  • Profile Page and Photo Upload in Spring Boot: Check the File, Shrink It, Keep Your Own Name
  • Building a Feature With an AI Agent, End to End: Comments on a Spring Boot Blog
  • Containerising Spring Boot: a Layered Dockerfile vs Buildpacks
  • GraalVM Native Image and Spring AOT: When It Pays, and What It Costs
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Scheduled Jobs in Spring Boot: fixedRate, fixedDelay, cron, and ShedLock for Many Instances
  • Redis in Spring Boot: a Cache, a Rate-Limit Counter and a Job Status Hash
  • Actuator and Micrometer in Spring Boot: Health, Your Own Metrics, and the Four Numbers That Matter
  • Structured Logging and Correlation IDs in Spring Boot: JSON Lines, a Filter and the MDC
  • Dashboards and Alerts for a Spring Boot App: Prometheus, Grafana and One Real Incident
  • Finding a Slow Spring Boot Endpoint: Actuator Timers, EXPLAIN ANALYZE and One Index
  • A GitHub Actions Workflow for a Maven Project: Cache, a Java Matrix and Test Reports That Survive a Red Run
  • The AWS SDK for Java v2 in Spring Boot: Clients as Beans, the Default Credentials Chain and No Keys in Code
  • Attachments in S3 from Spring Boot: Pre-signed Uploads, a 302 to a Pre-signed Download, and Links That Expire
  • CloudWatch for a Spring Boot App: JSON Logs, Micrometer Metrics From Your Own Code, and an Alarm That Reaches a Person
  • Automated Deploy, Smoke Test and Rollback for a Spring Boot App: Green Tests Are Not a Working Deploy
  • Environments, Secrets and Approvals in GitHub Actions: One Image From Staging to Production
  • Distributed Tracing Across Spring Boot Services and Kafka: One Trace ID From the Gateway to the Last Reader, Even Through an Outbox
  • Thymeleaf and htmx in Spring Boot: Live Search and One-Row Updates From Server-Rendered Fragments, With No JavaScript Framework
  • Rate Limiting, Backpressure and Load Shedding in Spring Boot: Bucket4j in Redis, a Bounded Worker Pool and Dropping Low-Priority Work
  • Resilience4j in Spring Boot: A Timeout, One Retry, a Circuit Breaker, a Bulkhead and a Fallback, Measured Against a Slow Dependency
  • Spring Boot Repository and Service Layer: Save and Read Data Without Writing SQL
  • Entities and H2 in Spring Boot: a Post Class Becomes a Table
  • Seed Data and Posts on the Homepage: CommandLineRunner, the Model and th:each
  • Pagination and Sorting on a Spring Boot Homepage: PageRequest In, Page Out
  • Connect Spring Boot to PostgreSQL: Driver, application.yml and the Hikari Pool
  • JPA Entity Mapping: Ids, Enums and Dates, From a Java Class to a Table
  • Spring Data Query Methods: Derived Queries, @Query and Projections
  • The N+1 Problem in JPA: Fetch Types, Join Fetch and Entity Graphs
  • Spring @Transactional: All or Nothing, the Proxy, and the Self-Call Trap
  • Flyway Migrations in Spring Boot: Numbered SQL Files, Seed Data and the History Table
  • Spring Data JPA Auditing and Soft Deletes: Who Changed It, When, and Hiding Instead of Deleting
  • Optimistic Locking with @Version: Two Agents, One Ticket, No Lost Update
  • Finding a Slow Spring Boot Endpoint: Actuator Timers, EXPLAIN ANALYZE and One Index
  • Caching With Spring and Redis: Cache-Aside, a TTL per Kind of Data, Eviction on Edit and Stopping the Stampede
  • A PostgreSQL Read Replica in Spring Boot: Route readOnly Transactions, Size the Pool, Find the Index, Read Your Own Writes
  • A Registration Form With Bean Validation in Spring Boot: @Valid, BindingResult and th:errors
  • Spring Security 7 Form Login, BCrypt and a UserDetailsService on the Account Table
  • Roles and Authorities at Login in Spring Security: From a ROLE Column to hasRole("ADMIN")
  • Menus per Role With Thymeleaf Security Tags: sec:authorize, sec:authentication and an Edit Button for the Author
  • Fixing the Access Bugs: a Rule per Role and an Ownership Check in Spring Security
  • Add, Edit and Delete Posts With a Rich-Text Editor in Spring Boot: Quill, jsoup and th:utext
  • Remember Me and Forgot Password by Email in Spring Boot: a Signed Cookie and a One-Time Link
  • Spring Boot Security Defaults: What One Dependency Gives You for Free
  • The Spring Security Filter Chain and Your Own Rules: 401, 403 and Rule Order
  • Stateless JWT Authentication in Spring Security: Sign Once, Check Every Request
  • Users in the Database with Spring Security: Register, BCrypt and Log In
  • Method Security in Spring: @PreAuthorize, Roles and Who Owns This Ticket
  • CORS and CSRF in Spring Security: Why the Browser Blocks Your SPA, and When CSRF Can Be Off
  • Reviewing AI-Written Spring Code for Security: Four Questions for Every Diff
  • Testing Secured Endpoints in Spring Boot: 401, 403 and 200 with @WithMockUser
  • An API Gateway With Spring Cloud Gateway: Check the JWT Once at the Edge, Pass the Caller Inward, and Know What the Network Now Trusts
  • Unit Tests With AI for a Spring Boot Service: Mockito Mocks, Given-When-Then and a Green Run
  • Docker for a Spring Boot App: Run the Tests in the Image Build, or Skip Them on Purpose
  • The Test Pyramid in Spring Boot: Unit, Slice and Whole-App Tests
  • Mockito and Test Doubles: Stubs, Mocks and Fakes for One Java Class
  • Spring Boot Test Slices: @WebMvcTest with MockMvc and @DataJpaTest
  • Integration Tests with Testcontainers: A Real PostgreSQL for Every Spring Boot Test Run
  • Testing Secured Endpoints in Spring Boot: 401, 403 and 200 with @WithMockUser
  • Test-First with a Coding Agent: Spec, Red Tests, Then the Code
  • Quality and Security Gates for a Maven Project: JaCoCo Coverage, PMD, an SBOM and a Trivy Scan
  • Testing Spring AI Features: a Stub ChatModel, Must-Cite and Must-Refuse Tests, and One Tagged Model Test
  • What Spring AI 2 Is, and Why a Java Team Wants It
  • Spring AI ChatClient: One API for Any Model, and the Model Is a Property
  • Spring AI Prompt Templates: Placeholders, Few-Shot Messages and Versioned Prompt Files
  • Spring AI Structured Output: From Model JSON to a Java Record, and a Real Ticket Triage Feature
  • Streaming Spring AI Answers to the Browser: stream(), a Flux of Server-Sent Events and the Cancel
  • Local Models With Ollama in Spring AI: Profiles, Per-Call Options and What a Smaller Model Costs
  • Testing Spring AI Features: a Stub ChatModel, Must-Cite and Must-Refuse Tests, and One Tagged Model Test
  • Embeddings and pgvector in Spring AI: EmbeddingModel, VectorStore, Distance Operators and the HNSW Index
  • RAG Ingestion in Spring AI: Parse Markdown, Chunk by Section, Embed Into pgvector With Stable Ids
  • Tuning Retrieval in Spring AI: Top-k, a Minimum Score, a Tenant Filter Inside the Query, Hybrid Search and a Reranker
  • Tool Calling in Spring AI 2: @Tool Methods, the ToolCallingAdvisor Loop and a Tool-Call Limit
  • Chat Memory in Spring AI: MessageChatMemoryAdvisor, a Conversation Id, a Window, a Summary and Where the State Lives
  • Building an MCP Server in Java With Spring AI: @McpTool, Stateless Streamable HTTP and Least-Privilege Tools
  • Consuming MCP Servers From Spring AI: a stdio Child Process and a Remote Streamable HTTP Server, Compared
  • A Supervisor and Specialist Agents in Spring AI: Own Prompts, Own Tools, Explicit State and a Menu Checked in Code
  • Choosing a JVM Agent Framework: the Same Two-Step Triage in Spring AI, LangChain4j Agentic and Embabel
  • Observability for Spring AI Calls: a Span per Feature, Token and Spend Counters, Jaeger Traces and Two Prometheus Alerts
  • Evals and Cost Control for a Java Subtitle Service: A Golden Set Scored by Word Error Rate in CI, and the Cost of One Hour of Audio From Micrometer Meters
  1. Blog
  2. /
  3. Spring Boot
  4. /
  5. Fundamentals

Thymeleaf and htmx in Spring Boot: Live Search and One-Row Updates From Server-Rendered Fragments, With No JavaScript Framework

A task board with live search and a Mark done button, rendered by Thymeleaf and updated by htmx attributes. Typing 'emma' sends GET /tasks?q=emma and the server answers with table rows only. Clicking Mark done posts to /tasks/2/done and gets back one row, which replaces the nearest tr. One fragment serves both the first load and every update.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

What you will learn

  • Write a Thymeleaf template that is still plain HTML, using th:text, th:if and th:classappend
  • Name fragments the server can render alone, and share one fragment between the first page load and every update
  • Return a fragment from a Spring MVC controller with the fragments :: name syntax
  • Wire live search and a Mark done button with hx-get, hx-post, hx-trigger, hx-target and hx-swap

Before you start

  • Spring MVC controllers
  • Basic HTML

A server-rendered page can still feel live. The old way reloads the whole page for every search or click, like a waiter bringing a brand new table for every plate. With htmx, only the piece that changed is swapped. This article builds a small task board in Spring Boot with Thymeleaf drawing the HTML on the server and htmx swapping in what the server sends back. You don't need to memorise every attribute, since AI can write them for you. The goal is to know what each one does, so you can judge the code.

A template is just HTML

<!-- One table row. "Mark done" posts and replaces just this row (hx-target="closest tr"). -->
<tr th:fragment="row(t)"
    th:id="|task-${t.id}|"
    th:classappend="${t.status == 'DONE'} ? 'done'">
  <td th:text="${t.title}">Task title</td>
  <td th:text="${t.owner}">Owner</td>
  <td><span class="badge" th:classappend="${t.status}"
            th:text="${#strings.replace(t.status, '_', ' ')}">TODO</span></td>
  <td class="act">
    <button th:if="${t.status != 'DONE'}" type="button"
            th:attr="hx-post=@{/tasks/{id}/done(id=${t.id})}"
            hx-target="closest tr" hx-swap="outerHTML">Mark done</button>
  </td>
</tr>

The th: attributes fill in the blanks. th:text replaces the placeholder, so without the server the cell says "Task title". th:if draws the button only when the task is not done. th:classappend adds the done class to a finished row. Open the file in a browser and it still looks like a page.

Named pieces the server can send alone

th:fragment="row(t)" makes that row a fragment, a named piece of HTML. A second fragment loops over the tasks:

<!-- All rows for the current search: used for the first page load AND as the live-search response -->
<th:block th:fragment="searchResults">
  <th:block th:each="t : ${tasks}">
    <tr th:replace="~{fragments :: row(${t})}"></tr>
  </th:block>
  <tr th:if="${#lists.isEmpty(tasks)}"><td colspan="4" class="empty">No tasks match.</td></tr>
</th:block>

The full page uses the same piece inside the table body:

<tbody id="rows">
  <th:block th:replace="~{fragments :: searchResults}"></th:block>
</tbody>

The page and the live search share one piece of HTML, so the first load and every update look exactly the same.

One page, two small answers

@Controller
public class BoardController {

    private final TaskRepository repo;

    public BoardController(TaskRepository repo) {
        this.repo = repo;
    }

    /** The full page (loaded once). */
    @GetMapping("/")
    String page(Model model) {
        model.addAttribute("tasks", repo.search(""));
        return "board";
    }

    /** htmx live search: returns only the table rows (a fragment), not a page. */
    @GetMapping("/tasks")
    String search(@RequestParam(defaultValue = "") String q, Model model) {
        model.addAttribute("tasks", repo.search(q));
        return "fragments :: searchResults";
    }

    /** htmx "Mark done": returns only the one updated row. */
    @PostMapping("/tasks/{id}/done")
    String done(@PathVariable int id, Model model) {
        Task t = repo.markDone(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
        model.addAttribute("t", t);
        return "fragments :: row(t=${t})";
    }
}

Returning "fragments :: searchResults" tells Thymeleaf to render one named piece of fragments.html instead of a whole page. The data is a record in an in-memory list of ten tasks, so the page stays the focus:

public record Task(int id, String title, String owner, String status) {
    public Task markDone() { return new Task(id, title, owner, "DONE"); }
}

TaskRepository.search lower-cases the text and keeps every task whose title or owner contains it. markDone replaces the task in the list with its done copy.

Live search

<!-- Live search: a pause in typing sends GET /tasks?q=... and swaps the rows into #rows -->
<input type="search" name="q" placeholder="Search by title or owner" autofocus autocomplete="off"
       hx-get="/tasks"
       hx-trigger="keyup changed delay:200ms, search"
       hx-target="#rows"
       hx-indicator="#rows">

hx-get says which address to call. hx-trigger says when: on a key up that changed the text, after a 200 ms pause. hx-target says where the answer goes.

Live search in four steps. You type emma and pause. The browser sends GET /tasks?q=emma. The server answers with only table rows, rendered from the searchResults fragment. htmx swaps them into the tbody with id rows, and the page never reloads. 1. Type "emma"pause 200 ms 2. GET /tasks?q=emmahx-get, hx-trigger 3. Rows onlyone fragment 4. Swap #rowsno reload The server stays in charge; the browser just swaps what it receives.
htmx is only attributes in the HTML.

The answer is table rows, not a page:

<tr id="task-1" class="done">
  <td>Design the landing page</td>
  <td>Emma</td>
  <td><span class="badge DONE">DONE</span></td>
  <td class="act">
  </td>
</tr>
<tr id="task-5">
...

Mark done: swap one row

The button in the row fragment has hx-post pointing at /tasks/{id}/done, hx-target="closest tr" so the target is the nearest row, and hx-swap="outerHTML", which replaces the row itself rather than its contents. Clicking it on task 2 sends POST /tasks/2/done, and the server answers with one row:

<tr id="task-2" class="done">
  <td>Build the task board screen</td>
  <td>Jack</td>
  <td><span class="badge DONE">DONE</span></td>
  <td class="act">
  </td>
</tr>

htmx replaces the nearest row with it. Before, the row had a Mark done button. After, it shows DONE with no button. One click, one tiny answer, one row changed.

One command to run it

FROM maven:3-eclipse-temurin-25 AS build
WORKDIR /app
COPY pom.xml .
RUN mvn -q -B dependency:go-offline
COPY src ./src
RUN mvn -q -B package -DskipTests

FROM eclipse-temurin:25-jre
WORKDIR /app
COPY --from=build /app/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
> docker compose up --build -d
 Container s04l02-thymeleaf-htmx-board-1  Started
> docker compose logs
:: Spring Boot ::                (v4.1.2)
Tomcat started on port 8080 (http) with context path '/'
Started ThymeleafHtmxApplication in 2.654 seconds (process running for 3.237)

Maven and Java 25 stay inside the containers. You only install Docker, then open localhost:8080. For full Thymeleaf pages with layouts, see Thymeleaf pages from a design.

Recap

PieceJob
Thymeleaf templateDraws the HTML on the server, and is still plain HTML
th:fragmentA named piece the server can send alone
"fragments :: row(t=${t})"The controller returns one piece, not a page
hx-get / hx-postWhat to call
hx-triggerWhen to call it
hx-target / hx-swapWhere the answer goes, and how it replaces what is there

Keep going in Spring Boot · 38 of 99

Previous
Distributed Tracing Across Spring Boot Services and Kafka: One Trace ID From the Gateway to the Last Reader, Even Through an Outbox
Next post
Rate Limiting, Backpressure and Load Shedding in Spring Boot: Bucket4j in Redis, a Bounded Worker Pool and Dropping Low-Priority Work
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed

Spring in one line: a container that creates your classes and hands each one what it needs. Plus the Spring Framework 7 baseline (JDK 17 to 25, Jakarta EE 11, Tomcat 11, JUnit 6), what got better than Spring 6, and a two-line version check.

A Plain Spring Project, No Boot: Your First Bean With spring-context

One dependency, one recipe, one getBean: a Maven project with spring-context 7.0.9, a Blog record, an AppConfig with @Bean, and a main that asks the container for the Blog. Then delete @Bean and meet NoSuchBeanDefinitionException.

Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways

A PostService needs a PostRepository. Build it three ways: the service calls new itself (tight coupling), main hands it in through the constructor (DI by hand), and the Spring container does the wiring from a @Configuration recipe.

Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods

Instead of one @Bean method per class, put @Component on EmailNotifier and PostService and @ComponentScan on an empty BlogConfig. Spring walks the package, finds the stickers and builds the beans; main doesn't change.

On this page

  • A template is just HTML
  • Named pieces the server can send alone
  • One page, two small answers
  • Live search
  • Mark done: swap one row
  • One command to run it
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.