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

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

    • 问题

    • 方案

    • Thymeleaf 基础语法

问题

使用 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项目

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

选择 Spring Boot 版本:2.1.18.RELEASE

选择所需依赖:

  • Lombok

  • Spring Web

  • Thymeleaf

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

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:name 和 th:value

URL写法

  • 通过@{...} 来处理URL的,需要使用 th:href 和 th:src 等属性,

  • <a th:href="@{http://xxx.com}">绝对路径</a>

  • <a th:href="@{/}">相对路径</a>

公众号

原文始发于微信公众号(知行chen):如何基于SpringBoot和Thymeleaf构建一个SpringMVC项目

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/45927.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!