Spring MVC and Thymeleaf Integration

Thymeleaf is an alternative as replacement of JSP, please visit http://www.thymeleaf.org/ for the further information about thymeleaf. Now I will show you how to integrate Spring MVC and Thymeleaf.

Maven Dependency :

<dependency>
	<groupId>org.thymeleaf</groupId>
	<artifactId>thymeleaf-spring4</artifactId>
	<version>2.1.4.RELEASE</version>
	<type>jar</type>
	<scope>compile</scope>
</dependency>

and the Java Configuration :

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.hidupbersahaja.controller" })
public class WebappConfig extends WebMvcConfigurerAdapter{
	
	private org.apache.commons.configuration.Configuration _config = ConfigManager.getConfiguration();
	
	
	/**
	 * Servlet Context Template Resolver
	 * @return
	 */
	@Bean
	public ServletContextTemplateResolver getServletContextTemplateResolver(){
		ServletContextTemplateResolver scTemplateResolver = new ServletContextTemplateResolver();
		scTemplateResolver.setPrefix("/WEB-INF/templates/");
		scTemplateResolver.setSuffix(".html");
		scTemplateResolver.setTemplateMode("HTML5");
		return scTemplateResolver;
	}
	
	/**
	 * Spring Template Engine 
	 * @return
	 */
	@Bean
	public SpringTemplateEngine getTemplateEngine(){
		SpringTemplateEngine templateEngine = new SpringTemplateEngine();
		templateEngine.setTemplateResolver(getServletContextTemplateResolver());
		return templateEngine;
	}
	
	/**
	 * Thymeleaf View Resolver
	 * @return
	 */
	@Bean
	public ThymeleafViewResolver getThymeleafViewResolver(){
		ThymeleafViewResolver resolver = new ThymeleafViewResolver();
		resolver.setTemplateEngine(getTemplateEngine());
		resolver.setOrder(1);
		return resolver;
	}
	
	/**
	 * Content Negotiate 
	 * to allowing request and respond content type 
	 * such as html, xml, json
	 */
	@Override
    public void configureContentNegotiation(
            ContentNegotiationConfigurer configurer) {
        configurer.defaultContentType(MediaType.TEXT_HTML)
                .mediaType("json", MediaType.APPLICATION_JSON)
                .mediaType("xml", MediaType.APPLICATION_XML)
                .favorPathExtension(true)
                .ignoreAcceptHeader(false); 
    }
}

and the Controller side :

@Controller
@RequestMapping("/faq")
public class FAQController {

	/**
	 * default handler
	 * 
	 * @return faq.html
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String defaultHandler(Model model) {
		return "faq";
	}
}

Create faq.html inside /WEB-INF/templates/ directory

<!doctype html>
<html lang="en">
<head>

</head>

<body>
	<h2>I am using Thymeleaf, how about you ? </h2>
</body>

</html>

That’s all … Good Luck

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>