5

Springboot + Htmx入门简单教程

 8 months ago
source link: https://www.jdon.com/71270.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Springboot + Htmx入门简单教程

Spring Boot是一个用于创建基于Java的企业级应用程序的框架,而htmx是一个用于构建动态Web应用的库。在这里,简要介绍如何将Spring Boot和htmx结合起来创建一个简单的Web应用。

1、创建Spring Boot项目:
使用Spring Initializr(https://start.spring.io/)创建一个新的Spring Boot项目。选择适当的项目元数据,然后添加Web依赖。下载并解压生成的项目文件。

2、添加依赖:
在生成的Spring Boot项目中,打开pom.xml文件,确保添加了htmx的依赖。你可以在htmx的官方网站(https://htmx.org/)找到相关信息。

   <groupId>org.webjars.npm</groupId>
    <artifactId>htmx.org</artifactId>
    <version>1.7.2</version>
</dependency>
这将使得htmx库可用于你的项目。

3、创建Controller:
创建一个简单的Spring Boot控制器,处理HTTP请求。

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MyController {

@GetMapping("/")
    public String home() {
        return "index";
    }
}

4、创建HTML页面:
在src/main/resources/templates目录下创建一个名为index.html的HTML文件。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Spring Boot + htmx</title>
    <!-- Add htmx script -->
    <script th:src="@{/webjars/htmx.org/1.7.2/dist/htmx.js}"></script>
</head>
<body>
    <h1>Spring Boot + htmx Example</h1>
    <button hx-get="/api/message" hx-swap="outerHTML">Load Message</button>
    <div id="message"></div>
</body>
</html>

在这个例子中,我们使用了htmx的hx-get属性来触发一个GET请求,并使用hx-swap属性将响应的内容替换掉原始的HTML内容。

5、创建Service:
创建一个简单的Spring Boot服务类,用于提供数据。

import org.springframework.stereotype.Service;

@Service
public class MyService {

public String getMessage() {
        return "Hello from the server!";
    }
}

6、更新Controller:
修改之前创建的Controller,以便在接收到请求时调用服务,并返回相应的数据。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

private final MyService myService;

@Autowired
    public MyController(MyService myService) {
        this.myService = myService;
    }

@GetMapping("/api/message")
    public String getMessage() {
        return myService.getMessage();
    }
}
这里使用了@RestController注解,表示这是一个RESTful风格的控制器,并且直接返回数据而不是视图。

7、运行应用:
启动Spring Boot应用,访问http://localhost:8080/,点击按钮,你应该能够看到从服务器加载的消息。

这只是一个简单的示例,演示了如何在Spring Boot应用中使用htmx。你可以根据实际需求扩展这个例子,添加更多的htmx特性和Spring Boot功能。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK