SpringBoot整合Thymeleaf

SpringBoot整合Thymeleaf

前言

对于动态数据,模板引擎会自动渲染并绑定,呈现动态页面。

Thymeleaf 是用来开发 Web 和独立环境项目的服务器端的 Java 模版引擎,与 SpringMVC 的视图技术,及 SpringBoot 的自动化配置集成非常完美。

与其他的模板引擎,例如 FreeMarker、JSP等相比,Thymeleaf语法更简单,功能更强大,SpringBoot 官方推荐使用 Thymeleaf。
p1

引入thymeleaf

使用 IDEA 建立 SpringBoot 项目的流程我们之前已经说过了,忘记了的重新回顾一下 SpringBoot入门

建立项目后记得更改端口号为8081,我们之后的页面访问都会在8081端口。

我们在建立 SpringBoot 项目时在初始化组件部分引入 thymeleaf 即可
p2

如果初始化组件部分没有选择 thymeleaf 也没有关系,我们可以直接在 pom.xml 文件中导入 thymeleaf 的依赖

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

thymeleaf的配置

thymeleaf支持的文件是 html 文件,默认的文件访问路径在 resource 目录的 templates 目录下

DEFAULT_PREFIX = “classpath:/templates/”
DEFAULT_SUFFIX = “.html”

当然,如果我们想自定义一个目录,可以在 application.properties 或者 application.yml 里面修改,比如我们定义在 resource 目录下的 public 目录

spring.thymeleaf.prefix=classpath:/public/
spring.thymeleaf.suffix=.html

要使用 thymeleaf,一定要在 html 文件中引入 thymeleaf 的命名空间

<html lang="en" xmlns:th="http://www.thymeleaf.org">

使用 thymeleaf 时有一个小技巧,我们可以在 application.properties 文件中禁用该模板引擎的缓存。禁用缓存之后,我们每次修改 html 文件,就不用重新启动项目了,按 Ctrl+F9 键就能实时编译 html 页面。

spring.thymeleaf.cache=false

第一个thymeleaf页面

如果 thymeleaf 文件默认的路径没有更改的话,在 templates 目录下创建 demo.html 文件。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf Demo</title>
</head>
<body>
    <h1>Welcome to thymeleaf</h1>
    <p th:text="${msg}"></p>
</body>
</html>

新建 controller目录,新建 DemoController类,在 DemoController 中进行设置

@Controller
public class DemoController {
    @GetMapping("/demo")
    public String demo(Model model){
        model.addAttribute("msg", "hhh");
        return "demo";
    }
}

注意,jsp中可以直接使用 ${xxx} 来显示后端传过来的
thymeleaf 中不能直接使用 ${xxx} 生成,得绑定在标签里

启动项目,打开浏览器,输入“localhost:8081/demo”即可看到页面成功显示
p3

thymeleaf语法

thymeleaf的语法比较简单。

th:任意html属性,替换原生属性的值

  • th:text,显示文本,不转义特殊字符
  • th:utext 转义特殊字符

我们使用表达式语法来获取变量的值:

  • ${···}:获取变量值
    • 获取对象的属性、调用方法
    • 内置工具对象可以通过#直接访问
<p th:text="${msg}"></p>
<p th:text="${#strings.toString(msg)}"></p>

*{···}:与 $ {···}功能一致,用来替代刚才 $ {···}选中的对象

<!--这两个元素获取的内容一样-->
<div th:object="${user}">
    <p th:text="${user.age}"></p>
    <p th:text="*{age}"></p>
</div>

对应的 controller 如下:

@Autowired
private User user;

@GetMapping("/demo")
public String demo(Model model){
    model.addAttribute("msg", "Alice");
    model.addAttribute(user);
    return "demo";
}

User实体类如下:

public class User {

    private String userName;
    private int age;
    private boolean flag;
    private Map<String, Object> map;
    private List<Object> list;
    private Laptop laptop;

    @Override
    public String toString() {
        return "User{" +
                "userName='" + userName + '\'' +
                ", age=" + age +
                ", flag=" + flag +
                ", map=" + map +
                ", list=" + list +
                ", laptop=" + laptop +
                '}';
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public Map<String, Object> getMap() {
        return map;
    }

    public void setMap(Map<String, Object> map) {
        this.map = map;
    }

    public List<Object> getList() {
        return list;
    }

    public void setList(List<Object> list) {
        this.list = list;
    }

    public Laptop getLaptop() {
        return laptop;
    }

    public void setLaptop(Laptop laptop) {
        this.laptop = laptop;
    }
}

@{···}:定义URL,在当前项目下直接跳转,或者请求静态资源

<a th:href="@{/demo}">hello</a>

其他的一些用法:

  • 文本操作
<p th:text="'this user is: '+${msg}">Bob</p>
  • 数学运算
<p th:text="'math calculate:1+1='+(1+1)"></p>
  • 条件运算
<p th:text="${user.flag} ? 'true' : 'false'"></p>

thymeleaf登录页面

在 static 目录下新建 asserts 目录,在asserts 目录下新建 css目录,在 css 目录下新建 login.css 文件。

*
{
    margin: 0;
    padding: 0;
}
.login_main {
    margin:7em auto;
    width: 24%;
    height: 30em;
    text-align: center;
}
.login_info
{
    font-size: 2em;
}
.login_textbox{
    width: 52%;
    height: 1em;
    font-size: 1em;
    margin: 2% 0;
    padding: 4%;
    color: gray;
    background-color: #f0f0f0;
    border: none;
    border-radius: 0.2em;
}
.login_btn
{
    width: 50%;
    height: 3em;
    background-color: #FFE4E1;
    margin: 2% 0;
}

在 templates 中新建一个 main.html 页面,作为登录之后的跳转页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>thymeleaf main</title>
</head>
<body>
this user has signed.
</body>
</html>

新建 login.html 文件,用 thymeleaf 写一个提交表单,向后台传值。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf login</title>
    <link th:href="@{/asserts/css/login.css}" rel="stylesheet">
</head>
<body>
    <form class="login_main" method="post" th:action="@{/logincheck}">
        <p class="login_info">Sign in</p>
        <input class="login_textbox" type="text" name="username" placeholder="username" required>
        <input class="login_textbox" type="password" name="password" placeholder="password" required>
        <button class="login_btn" type="submit">sign in</button>
        <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
    </form>
</body>
</html>

新建 LoginController类,后端先响应页面,使页面可以正常访问

@Controller
public class LoginController {
    @GetMapping("/login")
    public String login(){
        return "login";
    }
    @GetMapping("main")
    public String main(){
        return "main";
    }
}

后端再使用 RequestParam 接收数据。这里因为没有连接数据库,所以我们使用固定的登录账户密码。

@PostMapping("/logincheck")
public String check(@RequestParam("username") String name,
                    @RequestParam("password") String psw,
                    Map<String, Object> map){
    if(name.equals("kk") && psw.equals("123")){
        return "redirect:/main";
    }else{
        map.put("msg", "用户名或密码错误");
        return "login";
    }
}

运行项目,在浏览器地址栏输入“localhost:8081/login”,进入登录页面。
p4

输入错误的账户密码,页面会有提示
p5

输入正确的账户密码,成功跳转到 main.html 页面。
p6

参考文章

Thymeleaf简介

Thymeleaf 的基本用法

禁用thymeleaf模板引擎缓存

SpringBoot页面展示Thymeleaf

SpringBoot简单实现登录功能

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值