Configuring templateResolver & templateEngine in Java code

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Configuring templateResolver & templateEngine in Java code

tom123
Hi

The following is what you would use to configure your app to use jsp using @Configuration.


@Configuration
public class MvcBeans {

        // ...

        @Bean
        public InternalResourceViewResolver jspViewResolver() {
                InternalResourceViewResolver bean = new InternalResourceViewResolver();
                bean.setPrefix("/WEB-INF/views/");
                bean.setSuffix(".jsp");
                return bean;
        }

        @Bean
        public MultipartResolver multipartResolver() {
                return new CommonsMultipartResolver();
        }
}


It replaces the need for servlet-context.xml config.

Can this be defined for Thymeleaf also?
Reply | Threaded
Open this post in threaded view
|

Re: Configuring templateResolver & templateEngine in Java code

Zemi
Administrator
I have not tried it myself, but I think it should work, as Spring Java configuration is equivalent to Spring XML configuration.

For the Thymeleaf part, the examples in the Thymeleaf manual use Java code for configuration. See section 2.2 of "Using Thymleaf" tutorial
   http://www.thymeleaf.org/usingthymeleaf.html

Reply | Threaded
Open this post in threaded view
|

Re: Configuring templateResolver & templateEngine in Java code

tom123
Thanks Zemi.

That link was useful.

Here is my code incase anyone is interested.

@Configuration
@ImportResource({ "classpath*:contextConfig.xml",
		"classpath*:securityConfig.xml" })
@ComponentScan(basePackages = "com.webapp")
public class AppConfig
{
	@Bean
	public SpringTemplateEngine templateEngine()
	{
		SpringTemplateEngine templateEngine = new SpringTemplateEngine();

		ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();

		templateResolver.setTemplateMode(Consts.TEMPLATE_MODE_HTML5);
		templateResolver.setPrefix(Consts.TEMPLATE_LOCATION);
		templateResolver.setSuffix(Consts.TEMPLATE_SUFFIX_HTML);
		// templateResolver.setCacheTTLMs(3600000L);
		templateResolver.setCacheable(Boolean.FALSE);

		templateEngine.setTemplateResolver(templateResolver);
		return templateEngine;
	}

	@Bean
	public ThymeleafViewResolver thymeleafViewResolver()
	{
		ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver();

		thymeleafViewResolver.setTemplateEngine(this.templateEngine());

		return thymeleafViewResolver;
	}

	......
}