webhouse.appwebhouse.appdocs

Læs @webhouse/cms-indhold fra en Spring Boot-applikation. Reader-klasse, controllers, Thymeleaf-skabeloner.

Opsætning

Placér dit Spring Boot-projekt og @webhouse/cms-indhold side om side:

mit-projekt/
  cms.config.ts          # Skema (bruges af CMS admin)
  content/               # JSON-dokumenter (læses af Spring Boot)
  public/uploads/        # Mediefiler
  pom.xml
  src/main/java/...
  src/main/resources/templates/

Reader-klasse

Opret src/main/java/app/webhouse/cmsreader/WebhouseReader.java:

java
package app.webhouse.cmsreader;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Stream;

public final class WebhouseReader {
    private static final Pattern SAFE_NAME = Pattern.compile("^[a-z0-9]([a-z0-9-]*[a-z0-9])?$");

    private final Path contentDir;
    private final ObjectMapper mapper = new ObjectMapper();

    public WebhouseReader(String contentDir) {
        this.contentDir = Path.of(contentDir).toAbsolutePath().normalize();
    }

    public List<WebhouseDocument> collection(String collection, String locale) {
        validateName(collection);
        Path dir = contentDir.resolve(collection);
        if (!Files.isDirectory(dir)) return List.of();

        List<WebhouseDocument> docs = new ArrayList<>();
        try (Stream<Path> stream = Files.list(dir)) {
            stream.filter(p -> p.getFileName().toString().endsWith(".json")).forEach(p -> {
                try {
                    WebhouseDocument doc = mapper.readValue(p.toFile(), WebhouseDocument.class);
                    if (!"published".equals(doc.status)) return;
                    if (locale != null && !locale.equals(doc.locale)) return;
                    docs.add(doc);
                } catch (IOException ignored) { /* spring over */ }
            });
        } catch (IOException e) {
            return List.of();
        }
        docs.sort(Comparator.comparing(
            (WebhouseDocument d) -> d.getStringOr("date", ""),
            Comparator.reverseOrder()
        ));
        return docs;
    }

    public Optional<WebhouseDocument> document(String collection, String slug) {
        validateName(collection);
        validateName(slug);
        Path file = contentDir.resolve(collection).resolve(slug + ".json");
        if (!file.startsWith(contentDir) || !Files.isRegularFile(file)) {
            return Optional.empty();
        }
        try {
            WebhouseDocument doc = mapper.readValue(file.toFile(), WebhouseDocument.class);
            return "published".equals(doc.status) ? Optional.of(doc) : Optional.empty();
        } catch (IOException e) {
            return Optional.empty();
        }
    }

    public Optional<WebhouseDocument> findTranslation(WebhouseDocument doc, String collection) {
        if (doc.translationGroup == null) return Optional.empty();
        return collection(collection, null).stream()
            .filter(o -> doc.translationGroup.equals(o.translationGroup))
            .filter(o -> doc.locale == null || !doc.locale.equals(o.locale))
            .findFirst();
    }

    private static void validateName(String name) {
        if (name == null || !SAFE_NAME.matcher(name).matches()) {
            throw new IllegalArgumentException("Invalid name: " + name);
        }
    }
}

Spring-konfiguration

Registrér reader'en som en bean i din Application.java:

java
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public WebhouseReader webhouseReader() {
        return new WebhouseReader("content");
    }
}

Controller

java
@Controller
public class BlogController {
    private final WebhouseReader cms;

    public BlogController(WebhouseReader cms) {
        this.cms = cms;
    }

    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("posts", cms.collection("posts", "da"));
        return "home";
    }

    @GetMapping("/blog/{slug}")
    public String post(@PathVariable String slug, Model model) {
        WebhouseDocument post = cms.document("posts", slug)
            .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
        model.addAttribute("post", post);
        return "post";
    }
}

Thymeleaf-skabelon

html
<!-- src/main/resources/templates/post.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title th:text="${post.getString('title')}">Post</title>
</head>
<body>
    <article>
        <h1 th:text="${post.getString('title')}">Titel</h1>
        <time th:text="${post.getStringOr('date', '')}">dato</time>
        <div th:utext="${contentHtml}">indhold</div>
    </article>
</body>
</html>

Markdown-rendering

Brug commonmark-java til richtext-felter. Tilføj til pom.xml:

xml
<dependency>
    <groupId>org.commonmark</groupId>
    <artifactId>commonmark</artifactId>
    <version>0.24.0</version>
</dependency>

Opret en service der konverterer markdown til HTML og injicér den i din controller.

Servering af uploadede medier

I application.properties:

properties
spring.web.resources.static-locations=classpath:/static/,file:public/

Nu serveres /uploads/mit-billede.jpg fra public/uploads/mit-billede.jpg.

i18n: læs begge sprog

java
// Alle danske indlæg
List<WebhouseDocument> daPosts = cms.collection("posts", "da");

// Find oversættelsen af et specifikt indlæg
WebhouseDocument post = cms.document("posts", "hello-world").orElseThrow();
WebhouseDocument translation = cms.findTranslation(post, "posts").orElse(null);

Caching

Brug Spring's @Cacheable:

java
@Service
public class CachedWebhouse {
    private final WebhouseReader reader;

    @Cacheable("posts")
    public List<WebhouseDocument> posts(String locale) {
        return reader.collection("posts", locale);
    }
}

Invalidér via CMS admin webhook når indhold ændres.

Produktions-deployment

  • Fly.io / Render / Heroku — Spring Boot-apps virker ud af boksen
  • Bare-metal Tomcat — skift packaging til war i pom.xml
  • Docker — multi-stage build med eclipse-temurin:21-jre-alpine
  • AWS Beanstalk / Azure App Service — native Java-support

Fremtid: Maven Central-pakke

I F125 Phase 2 vil denne reader blive publiceret til Maven Central som app.webhouse:cms-reader så du kan:

xml
<dependency>
    <groupId>app.webhouse</groupId>
    <artifactId>cms-reader</artifactId>
    <version>0.1.0</version>
</dependency>

Indtil videre, kopiér WebhouseReader.java og WebhouseDocument.java filerne ind i dit projekt (~150 linjer i alt).

Næste skridt

Tags:FrameworksFilesystem Adapter
Forrige
Schema-eksport — webhouse-schema.json
Næste
Forbrug fra Laravel (PHP)
JSON API →Edit on GitHub →