温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring MVC和Thymeleaf模板引擎的集成方式是什么

发布时间:2024-06-05 16:32:10 来源:亿速云 阅读:92 作者:小樊 栏目:web开发

Spring MVC和Thymeleaf模板引擎的集成方式如下:

  1. 添加Thymeleaf依赖:首先需要在项目的pom.xml文件中添加Thymeleaf的依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  1. 配置Thymeleaf视图解析器:在Spring MVC的配置类中配置Thymeleaf视图解析器,示例代码如下:
@Configuration
public class ThymeleafConfig implements WebMvcConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        registry.viewResolver(resolver);
    }

    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.addDialect(new LayoutDialect());
        templateEngine.setEnableSpringELCompiler(true);
        templateEngine.setTemplateResolver(templateResolver());
        return templateEngine;
    }

    private ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setPrefix("classpath:/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        return templateResolver;
    }
}
  1. 创建Thymeleaf模板文件:在src/main/resources/templates目录下创建Thymeleaf模板文件,例如index.html,示例代码如下:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Spring Boot Thymeleaf Example</title>
</head>
<body>
    <h1 th:text="${message}"></h1>
</body>
</html>
  1. 创建Controller类:创建一个Spring MVC的Controller类,控制器方法中返回模板文件名称和数据,示例代码如下:
@Controller
public class HomeController {

    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("message", "Hello, Thymeleaf!");
        return "index";
    }
}

通过以上步骤,就可以实现Spring MVC和Thymeleaf模板引擎的集成,让Spring MVC控制器返回Thymeleaf模板文件,渲染动态页面。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI