Spring Boot integration FreeMarker template engine

POM

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

Project structure

src/
 +- main/
     +- java/
     |   +- com
     |       +- controller/
     |       |   +- IndexController.class
     |       +- Application.class
     +- resources/
         +- templates/
             +- index.ftlh
  • Application for the application startup class
  • IndexController the controller, which contains an index request processing method, which returns a string index, render the template file represents index.ftlh.
  • index.ftlh template file for the freemarker

Applciation.class

@SpringBootApplication
public class Application {

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

IndexController.class

@Controller
public class IndexController {

    @GetMapping("/index")
    public String index(Model model) {
        model.addAttribute("name", "Alice");
        return "index";
    }
}

Note @ResponseBody annotations can not be used in conjunction with freemarker, so here can not be marked @RestController comment.

index.ftlh

<!DOCTYPE html>
<html>
<head>
    <title>test</title>
</head>
<body>
hello ${name}!
</body>
</html>

run

Run Application class main method.

Then visit localhost: 8080 / index, results are presented as follows:

hello Alice!

Guess you like

Origin www.cnblogs.com/stronger-brother/p/12124784.html