# HTMX + Spring Boot Skill Package

**Created:** 2025-11-12
**Spring Boot Version:** 2.6+
**HTMX Version:** 2.0+

## Overview

Comprehensive skill package for building modern, interactive web applications using HTMX with Spring Boot 2.6+ and Thymeleaf templates. This skill enables server-side rendering with dynamic AJAX interactions using minimal JavaScript.

## Installation

1. Extract this package to your OpenCode skills directory:

   ```
   ~/.config/opencode/skills/htmx-spring-boot/
   ```

2. The skill will be available for use in OpenCode conversations.

## Contents

### Core Documentation

- `SKILL.md` - Main skill documentation with 10 core capabilities

### Reference Documentation (4 comprehensive guides)

- `references/spring-integration.md` - Spring Boot controller patterns, request detection, response headers, error handling, testing (~15,000 tokens)
- `references/thymeleaf-patterns.md` - Thymeleaf + HTMX integration, fragments, form handling, URL building, common patterns (~14,000 tokens)
- `references/htmx-attributes.md` - Complete HTMX attribute reference, triggers, swaps, events, extensions (~15,000 tokens)
- `references/security.md` - CSRF protection, Spring Security integration, authentication, authorization, XSS prevention (~12,000 tokens)

### Utility Scripts

- `scripts/validate_htmx.py` - Validate HTMX attributes in Thymeleaf templates
- `scripts/init_project.py` - Scaffold new Spring Boot + HTMX project
- `scripts/requirements.txt` - Python dependencies for scripts

### Template Assets

- `assets/layout/base.html` - Base layout with HTMX + CSRF setup
- `assets/fragments/form.html` - Reusable form components
- `assets/fragments/table.html` - CRUD table with HTMX
- `assets/fragments/modal.html` - Modal dialog templates
- `assets/examples/crud-app/` - Complete working CRUD example

## Quick Start

### 1. Add Maven Dependencies

```xml
<dependency>
    <groupId>io.github.wimdeblauwe</groupId>
    <artifactId>htmx-spring-boot</artifactId>
    <version>3.6.2</version>
</dependency>
<dependency>
    <groupId>io.github.wimdeblauwe</groupId>
    <artifactId>htmx-spring-boot-thymeleaf</artifactId>
    <version>3.6.2</version>
</dependency>
```

### 2. Create HTMX-Aware Controller

```java
@Controller
public class ItemController {

    @HxRequest
    @GetMapping("/items")
    public String listItems(Model model) {
        model.addAttribute("items", itemService.findAll());
        return "fragments/item-list"; // Returns HTML fragment
    }

    @HxRequest
    @PostMapping("/items")
    public HtmxResponse createItem(@Valid ItemForm form) {
        Item item = itemService.create(form);
        return HtmxResponse.builder()
            .view(new ModelAndView("fragments/item-row",
                  Map.of("item", item)))
            .trigger("item-created")
            .build();
    }
}
```

### 3. Use Thymeleaf Template with HTMX

```html
<form hx-post="/items" hx-target="#item-list" hx-swap="beforeend">
  <input name="name" required />
  <button type="submit">Add Item</button>
</form>

<div id="item-list">
  <div th:each="item : ${items}" class="item-row">
    <span th:text="${item.name}">Item name</span>
    <button
      hx:delete="@{/items/{id}(id=${item.id})}"
      hx-target="closest .item-row"
      hx-swap="outerHTML"
      hx-confirm="Delete this item?"
    >
      Delete
    </button>
  </div>
</div>
```

### 4. Configure CSRF Protection

```html
<!-- In layout head -->
<meta name="_csrf" th:content="${_csrf.token}" />
<meta name="_csrf_header" th:content="${_csrf.headerName}" />

<script>
  document.addEventListener("DOMContentLoaded", function () {
    document.body.addEventListener("htmx:configRequest", function (evt) {
      const token = document
        .querySelector('meta[name="_csrf"]')
        .getAttribute("content");
      const header = document
        .querySelector('meta[name="_csrf_header"]')
        .getAttribute("content");
      evt.detail.headers[header] = token;
    });
  });
</script>
```

## When to Use This Skill

Use the HTMX + Spring Boot skill when:

- **Building interactive web applications** with server-side rendering
- **Implementing CRUD operations** with minimal JavaScript
- **Adding dynamic content updates** without full page reloads
- **Validating forms** with inline server-side validation
- **Creating modern UIs** with progressive enhancement
- **Working with Thymeleaf fragments** for partial page updates
- **Handling HTMX-specific requests and responses** in Spring Boot
- **Securing HTMX endpoints** with CSRF protection and Spring Security
- **Testing HTMX controllers** with MockMvc

## Core Capabilities

1. **HTMX Request Detection** - Use `@HxRequest` annotation to create HTMX-specific endpoints
2. **Response Headers** - Set HTMX headers using annotations or `HtmxResponse` API
3. **Thymeleaf Integration** - Dynamic HTMX attributes with `hx:` namespace
4. **CRUD Patterns** - Complete examples for Create, Read, Update, Delete operations
5. **Out-of-Band Swaps** - Update multiple page sections in one response
6. **Form Validation** - Server-side validation with error handling
7. **Inline Validation** - Real-time field validation as users type
8. **Redirects** - Four redirect types (full reload, AJAX nav, refresh, string-based)
9. **CSRF Protection** - Secure HTMX requests with Spring Security
10. **Error Handling** - Global error handlers for HTMX requests

## Usage Examples

Ask OpenCode to:

- "Create an HTMX controller for user management with CRUD operations"
- "Add inline validation to this Thymeleaf form using HTMX"
- "Implement out-of-band swaps to update a counter and notification"
- "Set up CSRF protection for HTMX requests in Spring Security"
- "Generate a reusable Thymeleaf fragment for a sortable table with HTMX"
- "Create an infinite scroll component using HTMX and Spring Boot"
- "Add polling to this page section to refresh data every 30 seconds"
- "Implement a search-as-you-type feature with HTMX and Thymeleaf"

## Spring Boot 2.6 Compatibility

This skill is specifically designed for **Spring Boot 2.6.x** projects with these constraints:

- **No Java 17+ features**: No text blocks, no records
- **Spring Security 5.x**: Not compatible with Spring Security 6.x
- **Thymeleaf 3.0.x**: Use Thymeleaf 3.0 (not 3.1)
- **htmx-spring-boot 3.6.2**: Latest version compatible with Spring Boot 2.6

All code examples follow these constraints for drop-in compatibility.

## File Structure

```
htmx-spring-boot/
├── README.md                       # This file
├── SKILL.md                        # Main skill documentation
├── references/                     # Reference documentation
│   ├── spring-integration.md       # Spring Boot patterns
│   ├── thymeleaf-patterns.md       # Thymeleaf integration
│   ├── htmx-attributes.md          # HTMX attributes reference
│   └── security.md                 # Security best practices
├── scripts/                        # Utility scripts
│   ├── validate_htmx.py            # Template validator
│   ├── init_project.py             # Project scaffolder
│   └── requirements.txt            # Python dependencies
└── assets/                         # Template assets
    ├── layout/
    │   └── base.html               # Base layout template
    ├── fragments/
    │   ├── form.html               # Form components
    │   ├── table.html              # Table components
    │   └── modal.html              # Modal dialogs
    └── examples/
        └── crud-app/               # Complete CRUD example
            ├── ItemController.java
            ├── item-list.html
            ├── item-form.html
            └── item-row.html
```

## Key Features

### Request Detection

- `@HxRequest` annotation for HTMX-specific endpoints
- Conditional logic based on trigger element or target
- Automatic fragment rendering for HTMX requests

### Response Control

- Annotations: `@HxTrigger`, `@HxRetarget`, `@HxReswap`
- Programmatic: `HtmxResponse` builder API
- Out-of-band swaps with `FragmentsRendering`

### Template Integration

- `hx:` namespace for dynamic attributes
- URL building with Thymeleaf expressions
- Conditional HTMX based on user roles or state

### Security

- CSRF token integration with HTMX
- Spring Security authentication/authorization
- Input validation and XSS prevention
- Rate limiting with Bucket4j

### Testing

- MockMvc integration for HTMX endpoints
- Custom result matchers for HTMX headers
- Integration testing patterns

## Validation Scripts

### Template Validator

```bash
python scripts/validate_htmx.py templates/
```

Checks for:

- Missing CSRF tokens in forms
- Invalid hx-target selectors
- Invalid hx-swap values
- Common HTMX attribute mistakes

### Project Scaffolder

```bash
python scripts/init_project.py --name my-app --package com.example
```

Generates:

- Controller skeleton with HTMX endpoints
- Base layout with HTMX + CSRF setup
- Example fragments (form, table, modal)
- Maven dependencies configuration

## Common Patterns

### Infinite Scroll

```html
<div hx-get="/items?page=2" hx-trigger="revealed" hx-swap="afterend">
  Load More...
</div>
```

### Search as You Type

```html
<input
  name="query"
  hx-get="/search"
  hx-trigger="keyup changed delay:300ms"
  hx-target="#results"
/>
```

### Polling

```html
<div hx-get="/status" hx-trigger="every 30s" hx-swap="innerHTML">
  Status: Loading...
</div>
```

### Active Search

```html
<input
  name="search"
  hx-get="/search"
  hx-trigger="input changed delay:500ms, search"
  hx-target="#results"
  hx-indicator=".spinner"
/>
```

## External Resources

- [HTMX Official Documentation](https://htmx.org/)
- [htmx-spring-boot GitHub](https://github.com/wimdeblauwe/htmx-spring-boot)
- [Thymeleaf Documentation](https://www.thymeleaf.org/documentation.html)
- [Spring Boot 2.6 Reference](https://docs.spring.io/spring-boot/docs/2.6.x/reference/html/)

## Support

For comprehensive documentation and examples, refer to:

- `SKILL.md` - Main skill guide with 10 core capabilities
- `references/` - Four detailed reference documents (~56,000 tokens total)
- `assets/examples/` - Complete working CRUD application

## License

This skill package is provided as-is for use with OpenCode and Claude.
