如何基于SpringBoot和Thymeleaf构建一个SpringMVC项目

如何基于SpringBoot和Thymeleaf构建一个SpringMVC项目

问题

使用 Spring Boot 和 Thymeleaf 构建一个 SpringMVC 项目。

方案

场景模拟

实现了一个简单用户信息注册和信息展示场景,使用 Spring Boot 快速构建 Web 应用,并使用 Thymeleaf 作为模板引擎提供显示。

快速构建项目

使用 IDEA 的 Spring Initializr 构建

1.点击 File->New->Project 开始构建项目,选择 Spring Initializr ,

可以选择默认的 Spring 官方默认的工程脚手架 https://start.spring.io/ ,

使用 阿里云的 Spring Boot 工程脚手架 https://start.aliyun.com 。

详情见文章:如何快速构建一个Spring Boot项目

1.构建SpringBoot项目1

选择 Spring Boot 版本: 2.1.18.RELEASE

选择所需依赖:

  • Lombok
  • Spring Web
  • Thymeleaf

3.SpringBoot-常用注解使用在类名上的注解

MVC 分层开发Web应用

创建 Model

  • 创建用户信息类 User;
  • 使用 Lombok 简化代码,通过注解@Data 对象类编译后会自动生成 Getter、Setter等方法;
  • 使用 Spring Web 内置的 Hibernate-validator 实现数据的验证,常用注解有 @NotBlank 等。
@Data
public class User implements Serializable {
    private String id;
    @NotBlank(message = "用户不能为空")
    @Length(min = 5, max = 20, message = "用户名长度为5~20个字符")
    private String username;
    @Min(value = 18, message = "年龄不能小于18岁")
    @Max(value = 65, message = "年龄不能大于60岁")
    private Integer age;
}

创建 Controller

  • 创建包 controller ,在其下创建 UserController 类;
  • 使用注解 @RequestMapping 将 URL 映射到方法,
  • 创建方法:userForm(User user) 填写用户信息, addUser(User user) 添加用户信息, userInfo() 查看用户信息;
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {

    @GetMapping("/userForm")
    public ModelAndView userForm(){
        ModelAndView mav = new ModelAndView("userForm");
        User user = new User();
        mav.addObject("user", user);
        return mav;
    }

    @PostMapping("/addUser")
    public String addUser(@Valid User user, BindingResult bindingResult, RedirectAttributes attr){
        // 请求参数验证
        if(bindingResult.hasErrors()){
            return "userForm";
        }

        //TODO 持久化操作
        user.setId(UUID.randomUUID().toString());
        log.info("user:{}", user.toString());

        // 使用 attr 传递参数,暂存在 session ; redirect 防止重复提交
        attr.addFlashAttribute("user", user);
        return "redirect:/user/userInfo";
    }

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

}

创建 View

  • 使用模板引擎 Thymeleaf 提供模板渲染,在 src/main/resources/templates 创建模板文件 userForm.html
  • 在 HTML 模板文件中引入 Thymeleaf 的命名空间 <html lang="en" xmlns:th="http://www.thymeleaf.org">,以完成 Thymeleaf 的标签的渲染。
  • 编辑模板文件,创建需要填写的用户信息标签。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>User Form</title>
</head>
<body>
<form th:action="@{/user/addUser}" th:object="${user}" method= "post">
    <div>
        <span>用户名:</span>
        <span><input type="text" th:field="*{username}" /></span>
        <span class="warn" th:if="${#fields.hasErrors('username')}" th:errors="*{username}">名字错误</span>
    </div>
    <div>
        <span>年龄:</span>
        <span><input type="text" th:field="*{age}" /></span>
        <span class="warn" th:if="${#fields.hasErrors('age')}" th:errors="*{age}">年龄错误</span>
    </div>
    <div><button type="submit">提交</button></div>
</form>
</body>
</html>
  • 创建用户详情信息模板文件 userInfo.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>User Info</title>
</head>
<body>
<div>用户信息<a th:href="@{/user/userForm}">重新填写</a></div>
<div th:each="user:${user}">
    <div>ID:<span th:text="${user.id}">用户名称</span></div>
    <div>用户名:<span th:text="${user.username}">用户名称</span></div>
    <div>年龄:<span th:text="${user.age}">年龄</span></div>
</div>
</body>
</html>

启动服务

访问 http://127.0.0.1:8080/user/userForm ,填写用户信息,即完成了模拟 Spring MVC 的 Web应用程序构建。

Thymeleaf 基础语法

常用标签

  • th:text

    • <div th:text="${name}">name</div> 它用于显示控制器传入的name 值。
    • <span th:text="${name}?:'默认值'"></span> 如果name不存在,显示默认值。
  • th:object

    • th:object="${user}" 它用于接收后台传过来的对象。
  • th:action

    • <form th:action="@{/path}" method="post"></form> 它用来指定表单提交地址。
  • th:value

    • <input type="text" th:value="${article.id}" name="id" /> 它用对象id的值替换为value的属性。
  • th:field

    • <input type="text" id="title" name="title" th:field="${article.title}" /> 它用来绑定后台对象和表单数据。
    • Thymeleaf 里的 th:field 等同于 th:nameth:value

URL写法

  • 通过@{...} 来处理URL的,需要使用 th:hrefth:src 等属性,
  • <a th:href="@{http://xxx.com}">绝对路径</a>
  • <a th:href="@{/}">相对路径</a>

公众号

知行chen

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值