SpringBoot(8) - - SpringBoot整合Thymeleaf模板

项目地址:https://github.com/zhaopeng01/springboot-study/tree/master/study8

Spring Boot提供了多种模板引擎的默认配置支持,但嵌入式容器JSP有限制,2010年后Velocity停止更新,所以这JSP与Velocity两个不建议使用,然实际在企业中,还是有很多在使用

那么这里主要是springboot整合Thymeleaf模板。
SpringBoot使用上述模板,默认从src/main/resources/templates下加载。

Thymeleaf是现代化服务器端的Java模板引擎,不同与其它几种模板的是Thymeleaf的语法更加接近HTML,并且具有很高的扩展性,其他详细可移步官网

依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

先创建一个实体类
entity

package com.zyc.entity;

public class Person {
    private String name;
    private String gender;
    private String email;
//get set 方法
}

创建一个controller 用来映射HTTP请求与页面的跳转

controller

package com.zyc.controller;

import com.zyc.entity.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: Thymeleaf
 * @author zhaopeng
 * @email zp152527@163.com
 */

@Controller
@RequestMapping
public class ThyController {

    @GetMapping("/index")
    public ModelAndView index() {
        ModelAndView view = new ModelAndView();
        view.setViewName("index");
        // 设置属性
        view.addObject("title", "Thymeleaf页面");
        view.addObject("desc", "Welcome to Thymeleaf");
        Person person = new Person();
        person.setGender("男娃子");
        person.setEmail("77742344@qq.com");
        person.setName("赵鹏");
        view.addObject("person", person);
        return view;
    }

    @GetMapping("/index1")
    public String index1(HttpServletRequest request) {
        // 设置属性
        request.setAttribute("title", "Thymeleaf页面");
        request.setAttribute("desc", "Welcome to Thymeleaf");
        Person person = new Person();
        person.setGender("难道到这里就能变成个女娃子?");
        person.setEmail("77742344@qq.com");
        person.setName("赵鹏");
        request.setAttribute("person", person);
        return "index";
    }

}

两个方法的写法不同,但是结果一致。
在第一个方法中设置的跳转到index,默认映射到 src/main/resources/templates/{viewName}.html
在第一个方法中设置的跳转到index,默认映射到 src/main/resources/templates/xxxx.html

这样就基本ok了,可以先直接将这个index.html打开看一下,这是静态效果
在这里插入图片描述

然后运行我们的项目,访问 http://localhost:8080/index 然后可以看到我们的动态效果
在这里插入图片描述

SpringBoot 默认情况下为我们做了如下的默认配置工作,当然我们也可以在自己需要的情况下去修改这些配置,实现自己的需求
在这里插入图片描述

好的到这里本篇文章就先到此了,创作不易,如果那里有不合适的地方还请大家多多指教,写这篇博的目的主要就是为了方便自己以后的一个回忆和朋友学习时的一个参考,希望为大家可以带来帮助 ~ ~&

虚心的去学习,自信的去工作~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值