freemarker和thymeleaf都需要分别加入两个configuration类:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.templateresolver.FileTemplateResolver;
import javax.annotation.PostConstruct;
@Configuration
public class config {
@Autowired
private SpringTemplateEngine templateEngine;
@PostConstruct
public void extension() {
FileTemplateResolver resolver = new FileTemplateResolver();
resolver.setPrefix("/Applications/java/templates/");
resolver.setSuffix(".html");
resolver.setTemplateMode("HTML5");
resolver.setOrder(templateEngine.getTemplateResolvers().size());
resolver.setCacheable(false);
templateEngine.addTemplateResolver(resolver);
}
}
import freemarker.cache.FileTemplateLoader;
import freemarker.template.TemplateException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
import java.io.File;
import java.io.IOException;
@Configuration
public class MvcConfigurer {
@Bean
public ViewResolver viewResolver() {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
resolver.setCache(false);
resolver.setPrefix("");
resolver.setSuffix(".html");
resolver.setContentType("text/html; charset=UTF-8");
return resolver;
}
@Bean
public FreeMarkerConfigurer freemarkerConfig() throws IOException, TemplateException {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer() {
protected void postProcessConfiguration(freemarker.template.Configuration config) throws IOException, TemplateException {
FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(new File("/Applications/java/templates/"));
config.setTemplateLoader(fileTemplateLoader);
}
};
configurer.setDefaultEncoding("UTF-8");
configurer.setPreferFileSystemAccess(false);
return configurer;
}
}