中文字幕精品亚洲无线码二区,国产黄a三级三级三级看三级,亚洲七七久久桃花影院,丰满少妇被猛烈进入,国产小视频在线观看网站

springboot~手動(dong)加載thymeleaf模版

thymeleaf在spring-mvc時(shi)代很是盛行,與freemaker組成(cheng)了(le)兩大模(mo)(mo)版(ban)引擎(qing),而進行springboot之后(hou),很多項目都(dou)采用前(qian)后(hou)分(fen)離的(de)模(mo)(mo)式,這(zhe)使(shi)得模(mo)(mo)板引擎(qing)關注(zhu)度少了(le);而在一些場景下,使(shi)用模(mo)(mo)板引擎(qing)還是有著(zhu)不可替代的(de)優勢的(de),比(bi)如email模(mo)(mo)板,我(wo)們會把html模(mo)(mo)版(ban)文件(jian)和后(hou)端代碼放到一個(ge)項目,這(zhe)樣部署更方便(bian),組件(jian)的(de)內聚性(xing)更強。

  • 定義自己的模塊引擎
/**
 * 定義一個目錄為資源根目錄的引擎
 * @author lind
 * @date 2022/8/18 9:04
 * @since 1.0.0
 */
@Configuration
public class EngConfig {
    @Bean("rootEngine")
    public SpringTemplateEngine springTemplateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.addTemplateResolver(htmlTemplateResolver());
        return templateEngine;
    }
    @Bean
    public SpringResourceTemplateResolver htmlTemplateResolver(){
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setPrefix("classpath:/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
        return templateResolver;
    }
}
  • 在需要使用email的地方,直接通過SpringTemplateEngine的process方法來渲染html模板
@RestController
@RequiredArgsConstructor
public class MailController {
    private final SpringTemplateEngine springTemplateEngine;
    private String template = "META-INF/spring/mail.html";

    /**
     * 發送email.
     *
     * @return
     */
    @GetMapping("/mail/send")
    public String send() {
        Context ctx = new Context();
        ctx.setVariable("message", "zhangsan");
        return springTemplateEngine.process(this.template, ctx);
    }
}
  • mail.html很簡單,里面有個message的變量,由上面的后端代碼傳入
<html xmlns:th="//www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

</head>
<body>
<h2 th:text="${message}" />
</body>
</html>

posted @ 2022-08-18 09:21  張占嶺  閱讀(754)  評論(0)    收藏  舉報