MTI TEK
Spring Framework | Spring MVC

Spring MVC with Thymeleaf

Spring MVC — Overview

Dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

@Controller and View Name Resolution

@Controller
public class HomeController {
    @GetMapping("/")
    public String home() {
        // returns logical view name "home"
        // resolved to /src/main/resources/templates/home.html
        return "home";
    }
}

Static Resources vs. Thymeleaf Templates

# With Thymeleaf autoconfiguration active, these are ignored unless ThymeleafViewResolver precedence is explicitly lowered:
#spring.mvc.view.prefix=classpath:/static/
#spring.mvc.view.suffix=.html

@WebMvcTest Slice

@WebMvcTest(HomeController.class)
public class HomeControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testHomePage() throws Exception {
        mockMvc.perform(get("/"))
               .andExpect(status().isOk())
               .andExpect(view().name("home"))
               .andExpect(content().string(containsString("Welcome to MTITEK Spring MVC.")));
    }
}