Spring Boot入门样例-060-thymeleaf模板引擎

Spring Boot入门样例-060-thymeleaf模板引擎

已经可以将数据库中数据读取出来,该在前端显示漂亮的界面。本demo演示如何使用thymeleaf模板引擎渲染出一个简单的登录界面。

前言

本Spring Boot入门样例准备工作参考:

pox.xml

必要的依赖如下,具体参见该项目的pox.xml

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

配置文件

resources/application.yml配置内容

spring:
  thymeleaf:
    cache: false
    servlet:
      content-type: text/html
    mode: HTML
    encoding: UTF-8

代码解析

该项目有很多目录,分别说明如下:

  • controller目录为控制器文件
  • entity目录为实体目录,对应表格中的字段(本样例不查询数据库)
  • resources/templates对应模板文件路径
  • resources/static静态文件路径,包括css和images图片

User.java 每个字段对应表格一个字段(本样例不查询数据库,先不对应)

@Data
public class User {
    private String name;
    private String password;
}

SiteController.java 如下

@Controller
public class SiteController {

    @GetMapping({"", "/", "index"})
    public String index(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        if (user  == null) {
            return "redirect:/login";
        }
        request.setAttribute("user", user);
        return "site/index";
    }

    @GetMapping("/login")
    public String login() {
        return "site/login";
    }

    @PostMapping("/login")
    public String save(@ModelAttribute User modelAttribute, BindingResult result, HttpServletRequest request) {
        if (result.hasErrors()) {
            return "binding error";
        }
        request.getSession().setAttribute("user", modelAttribute);
        return "redirect:/";
    }
}

  1. index方法先判断是否登录,否则跳转login
  2. get的login方法显示resources/templates/site/login.html文件,该文件会引入resources/templates/common/head.html,以及使用resources/static中的css和图片文件
  3. 登录后显示resources/templates/site/index.html中内容

运行

点击运行

浏览器访问 http://localhost:8080/
浏览器访问 http://localhost:8080/login

图片
图片

参考

  • Spring Boot入门样例源代码地址 https://github.com/funsonli/spring-boot-demo
  • Bootan源代码地址 https://github.com/funsonli/bootan

如果您喜欢本Spring Boot入门样例和样例代码,请点赞Star

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值