Currently, I am doing a small project in which I need to use Spring Boot and FreeMarker template engine. I have tried different ways but I still cannot return a FreeMarker view from Spring Boot. My project uses Gradle as the build tool, here's what's inside:
build.gradle:
plugins {
id 'org.springframework.boot' version '2.3.3.RELEASE'
id 'java'
}
apply plugin: 'io.spring.dependency-management'
sourceCompatibility = 11
repositories {
mavenCentral()
}
sourceSets.main.resources.srcDirs = ["src/resources"]
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
compile("org.springframework.boot:spring-boot-starter-web")
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'org.springframework.boot:spring-boot-starter-freemarker'
}
Here is my method which I expect to redirect to the FreeMarker view with a list, instead, when I send a GET request to this URL, I just get the "index
" string displayed:
@GetMapping(path = "/code/latest")
public String getTop10LatestCode(@ModelAttribute("model") ModelMap model) {
model.addAttribute("codes", codes.subList(Math.max(0, codes.size() - 10), Math.max(codes.size() - 1, 0)));
return "index";
}
Here is my application.properties
file:
server.port=8889
management.endpoints.web.exposure.include=*
management.endpoint.shutdown.enabled=true
spring.freemarker.template-loader-path=classpath:/templates/
spring.freemarker.suffix=.ftlh
My FreeMarker view is already under the templates
folder inside the resources
folder.
Here is my project structure:
Any help would be much appreciated, thanks.
I have figured it out, my class is annotated with the @RestController
annotation, which itself is the combination of the @Controller
and @ResponseBody
annotations, because each method in my class will have a response body returned, even the one that I posted here, that's why it returns the body, hence returns index
. I need to change my @RestController
to @Controller
and the problem solved.