The folder structure for this example is as below.
Here we need the thymeleaf artifactId to render HTML views.
springdemo/ │ ├── pom.xml └── src/ └── main/ ├── java/ │ └── com/ │ └── example/ │ └── springdemo/ │ ├── Application.java │ └── controller/ │ └── GreetingController.java └── resources/ └── templates/ └── greeting.html
Application.java
package com.example.springdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }GreetingController.java
package com.example.springdemo.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class GreetingController { @GetMapping("/greeting") public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) { // Pass the name variable to the HTML template model.addAttribute("name", name); // Returns the name of the HTML file (greeting.html) return "greeting"; } }greeting.html
<!DOCTYPE html> <html xmlns:th="http://thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Spring Boot Greeting</title> </head> <body> <!-- Thymeleaf replaces the placeholder text with the actual dynamic value --> <h1 th:text="'Hello, ' + ${name} + '!'">Hello, User!</h1> </body> </html>pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://apache.org" xmlns:xsi="http://w3.org" xsi:schemaLocation="http://apache.org https://apache.org"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.2.5</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>springdemo</artifactId> <version>0.0.1-SNAPSHOT</version> <name/> <description>Demo project for Spring Boot</description> <properties> <java.version>17</java.version> </properties> <dependencies> <!-- Spring MVC for Web development --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Thymeleaf for rendering HTML views --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
No comments:
Post a Comment