Spring boot에서 java 변수값을 템플릿에 출력하기

2024. 11. 17. 15:44Java/Spring Boot

java

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

@Controller
public class MyController {

    @GetMapping("/show-variable")
    public String showVariable(Model model) {
        String message = "Hello, Spring Boot!";
        model.addAttribute("myVariable", message); // Add the variable to the model
        return "template"; // Return the name of the template file
    }
}

template

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Display Variable</title>
</head>
<body>
    <h1>Displaying a Variable</h1>
    <p>Value of myVariable: <span th:text="${myVariable}"></span></p>
</body>
</html>

output

Value of myVariable: Hello, Spring Boot!