SpringBoot:Thymeleaf集成


    org.springframework.boot
    spring-boot-starter-thymeleaf

配置ClassLoaderTemplateResolver:

/**
 * Function:  todo
 *
 * @program: TemplateConfig 
 * @Package: com.kingbal.tohtml.tst
 * @author: dingcho
 * @date: 2024/09/06
 * @version: 1.0
 * @Copyright: 2024 www.kingbal.com Inc. All rights reserved.
 */
@Configuration
public class TemplateConfig {
 
    @Bean
    public ClassLoaderTemplateResolver templateResolver() {
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        // 设置模板引擎,例如THYMELEAF或者FREEMARKER
        templateResolver.setPrefix("templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        // 可以设置其他属性,例如模板编码等
        templateResolver.setCharacterEncoding("UTF-8");
        return templateResolver;
    }
 
    @Bean
    public SpringTemplateEngine templateEngine(ClassLoaderTemplateResolver templateResolver) {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        return templateEngine;
    }
 
    @Bean
    public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine);
        return viewResolver;
    }
}

在这个配置中,所有的模板文件都被放置在src/main/resources/templates目录下,并且都有.html后缀。ClassLoaderTemplateResolver会自动查找这些模板

在Controller中使用模板:

/**
 * Function:  todo
 *
 * @program: HtmlController
 * @Package: com.kingbal.tohtml.tst.controller
 * @author: songjianlin
 * @date: 2024/08/09
 * @version: 1.0
 * @Copyright: 2024 www.kingbal.com Inc. All rights reserved.
 */
@RestController
@RequestMapping("/v1/index/html")
@AllArgsConstructor
public class HtmlController {

    private final TemplateEngine templateEngine;
 
    @PostMapping("/create")
    public voidcreate() {
        String path = "D:\\git\\html";
        File file=new File(path);
        if(!file.exists()){
            file.mkdir();
        }
        FileWriter writer = new FileWriter(file.getPath() + "\\index.html");
        //创建Context对象(存放Model)
        Context context = new Context();
        context.setVariable("title", "测试列表");
        templateEngine.process("index", context, writer);
    }
}

你可能感兴趣的:(前端,SpringCloud,spring,boot,Thymeleaf集成)