I am newbie with Spring, Themeleaf and Beans. I created my on Java Bean and I want to display staff mainly text in html.
This is my Bean
package com.example.platformylab03;
import org.springframework.stereotype.Component;
@Component
public class Book {
private String author;
private String title;
public Book() {
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Obvious SpringBootApp:
package com.example.platformylab03;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PlatformyLab03Application {
public static void main(String[] args) {
SpringApplication.run(PlatformyLab03Application.class, args);
}
}
And my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Hello</h1>
<p th:text="${Book.author}" />
</body>
</html>
If possible please explain it on code sample or link me useful page. Thanks <3
CodePudding user response:
First, you need to create a controller:
@Controller
public class MyController {
@GetMapping("/page")
public String main(Map<String, Object> model) {
Book book = new Book();
book.setAuthor("Alastair Reynolds");
book.setTitle("Revelation Space");
model.put("book", book);
return "page";
}
}
Then make sure you're template is named "page.html" (same as the return string on your controller). I put mine in Other Sources/templates/page.html
.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Hello</h1>
<p th:text="${book.author}" />
</body>
</html>
Once everything is linked together, access /page/
on your server.