SpringBoot下我们需要引入Thymeleaf作为模板引擎输出HTML(例如渲染出邮件的HTML或者输出PDF用的HTML等等),但是并不需要它作为view来输出(viewResolver)(例如项目中已经使用了JSP来做view输出了)。
关于SpringBoot整合JSP详见:https://blog.terrynow.com/2021/07/07/springboot-mvc-jsp-and-jstl-implment/
首先,我们在SpringBoot的pom.xml引入了:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
不过引入spring-boot-starter-thymeleaf后,之前JSP做view输出也失效了,转而默认的输出是用的Thymeleaf
让Thymeleaf只输出html,不做view输出的具体实现
修改application.yml(或者application.properties)中关闭thymeleaf
spring:
thymeleaf:
enabled: false
如果是application.properties里:
spring.thymeleaf.enabled=false
增加ThymeleafConfig.java 配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;
import java.nio.charset.StandardCharsets;
/**
* @author Terry E-mail: yaoxinghuo at 126 dot com
* @date 2021/12/23 16:18
* @description
*/
@Configuration
public class ThymeleafConfig {
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
springTemplateEngine.setTemplateResolver(templateResolver());
return springTemplateEngine;
}
@Bean
public ITemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setTemplateMode(TemplateMode.HTML5);
// templateResolver.setPrefix("/WEB-INF/templates/"); // 模板文件的位置,如果你放在webapp/WEB-INF/templates下就这样写
templateResolver.setPrefix("classpath:/templates/"); // 模板文件的位置,如果你放在resources/templates下就这样写
templateResolver.setSuffix(".html");
templateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
templateResolver.setCacheable(false); // 禁用缓存
return templateResolver;
}
}
接下来可以使用了,在service中可以这样调用:
@Autowired
private TemplateEngine templateEngine;
public void someMethodInService() {
Context context = new Context();
context.setVariable("title", "SomeTitle");
// 利用 Thymeleaf 输出渲染好的 html
String html = templateEngine.process("template_name", context);
}
文章评论