这一部分的代码是基于大神的代码,只是原本的代码是有错的,只自己记录一下自己更改之后的代码和自己的理解。

  使用Spring Initzal创建项目,最后代码结构如下,我对Spring及其相关之事还是全然陌生的,只按自己理解的话,UserController处定义了浏览器接口,resposity文件夹中的两个文件定义了User类的增删查改,这些增删查改的操作又会被前端通过接口访问,这段代码对于想偷懒的我稍稍有点复杂,但是可以看出比较多的知识点:

  

使用Thymeleaf的过程:

  1、写代码前的配置

    在pom.xml中添加依赖

    

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

    在application.properties中添加对Thymeleaf的配置

 

#Thymeleaf
#指定编码方式
spring.thymeleaf.encoding=UTF-8 #热部署静态文件。能够在浏览器中及时看到修改后的效果(开发)
spring.thymeleaf.cache=false #使用html5标准
spring.thymeleaf.mode=html5

  2、编写User类和reponsitory里的代码

    User类:这里的成员变量id、name、age都是私有的,但其实我在前端界面直接调用实例的id、name、age好像都可以,并不报错

public class User {
private Long id;//唯一标识
private String name;
private Integer age;
public User() {//无参默认构造器
}
public User(Long id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}

User类

    UserRepository接口

import com.example.demo.domain.User;

import java.util.List;

public interface UserRepository {
User saveOrUpdateUser(User user); //新增或者修改用户 void deleteUsere(Long id); //删除用户 User getUserById(Long id); //根据用户id获取用户 List<User> userList (); //获取所有用户的列表 }

UserRepository接口

    UserRepositoryImpl 类:这里增删查改只是模拟保存,没有涉及到真正的保存,重跑就会丢失数据

import com.example.demo.domain.User;
import org.springframework.stereotype.Repository; import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong; @Repository//用于标识UserRepositoryimpl 类是一个可注入的bean 。
public class UserRepositoryImpl implements UserRepository { //用来生成一个递增的id ,作为用户的唯一编号。
private static AtomicLong counterId = new AtomicLong(); //模拟数据的存储,
private final ConcurrentMap<Long , User> userConcurrentMap =new ConcurrentHashMap<Long,User>(); @Override
public User saveOrUpdateUser(User user) {
Long id =user.getId();
if (id==null){
id=counterId.incrementAndGet();
user.setId(id);
}
this.userConcurrentMap.put(id,user);
return user;
} @Override
public void deleteUsere(Long id) {
this.userConcurrentMap.remove(id); } @Override
public User getUserById(Long id) {
return this.userConcurrentMap.get(id);
} @Override
public List<User> userList() {
return new ArrayList<User>(this.userConcurrentMap.values());
}
}

UserRepositoryImpl 类

  3、前端界面代码

    看这前端的代码数量就知道我为什么嫌弃复杂了,在这里面common文件夹下的明显是可公用的模块(像页眉、页脚这种存在),list是展示所有用户、form界面是新建和编辑用户的可编辑页面,view是进入某个用户的详情页。   

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>页脚</title>
</head>
<body>
<div th:fragment="footer">
<a href="/helloworld">欢迎光临</a>
</div>
</body>
</html>

common/footer.html

common/footer.html:在这里定义了fragment="footer"的片段
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>页头</title>
</head>
<body>
<div th:fragment="header">
<h1>DemoThymeleaf</h1>
<a href="/user" th:href="@{~/user/userlist}">首页</a>
</div>
</body>
</html>

common/header.html

common/header.html:在这里定义了fragment="header"的片段
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
</head>
<body>
<div th:replace="~{common/header::header}"></div>
<h4 th:text="${userModel.title}">
渡西湖
</h4>
<div>
<a href="/user/form" th:href="@{/user/form}">
新建用户
</a>
</div>
<table border="2">
<thead>
<tr>
<td>id</td>
<td>名字</td>
<td>年龄</td>
<td>管理</td>
</tr>
</thead>
<tbody>
<tr th:if="${userModel.userList.size()} eq 0">
<td colspan="3">无数据!</td>
</tr>
<tr th:each="user:${userModel.userList}">
<td th:text="${user.getId()}"></td>
<td><a th:href="@{'/user/'+${user.getId()}}" th:text="${user.getName()}"></a></td>
<td th:text="${user.getAge()}"></td>
<td><a th:href="@{'/user/delete/'+${user.getId()}}">删除</a></td>
</tr>
</tbody>
</table>
<div th:replace="~{common/footer::footer}"></div>
</body>
</html>

user/list.html

 user/list.html:
    1、使用<div th:replace="~{common/header::header}"></div>引用了在commmon/header.html中的片段
   2、使用${}获取传入数据
   3、使用@{}获取controller中定义的地址
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout= "http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title>DemoThymeleaf</title>
</head>
<body>
<div th:replace="~{common/header::header}"></div>
<h4 th:text="${userModel.title}"></h4>
<form action="/user" th:action="@{/user}" method="post" th:object="${userModel.user}">
<input type="hidden" name="id" th:value="*{id}"/>
名字<br/>
<input type="text" name="name" th:value="*{name}"/>
<br/>
<input type="number" name="age" th:value="*{age}"/>
<br/>
<input type="submit" value="提交">
</form>
<div th:replace="~{common/footer::footer}"></div>
</body>
</html>

user/form.html

 user/form.html:这里包含了对form元素的处理,绑定了object,并使用*{}为输入绑定object里面对应的值,可以直接将数据传到后端
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户详情</title>
</head>
<body>
<div th:replace="~{common/header::header}"></div>
<h4 th:text="${userModel.title}"></h4>
<div>
<p><strong>ID:</strong><span th:text="${userModel.user.id}"></span></p>
<p><strong>名字:</strong><span th:text="${userModel.user.name}"></span></p>
<p><strong>年龄:</strong><span th:text="${userModel.user.age}"></span></p>
</div>
<div>
<a th:href="@{'/user/delete/'+${userModel.user.id}}">删除</a>
<a th:href="@{'/user/edit/'+${userModel.user.id}}">修改</a>
</div>
<div th:replace="~{common/footer::footer}"></div>
</body>
</html>

user/view.html

  4、controller的编写

import com.example.demo.domain.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView; @RestController
@RequestMapping("/user")
public class UserController { @Autowired
private UserRepository userRepository; //查词所有用户
@GetMapping("/userlist")
public ModelAndView userList(Model model){
model.addAttribute("userList",userRepository.userList());
model.addAttribute("title","用户管理");
return new ModelAndView("user/list","userModel",model);
}
//根据id 查询用户
@GetMapping("{id}")
public ModelAndView view(@PathVariable("id") Long id, Model model){
User user= userRepository.getUserById(id);
model.addAttribute("user",user);
model.addAttribute("title","查看用户");
return new ModelAndView("user/view" ,"userModel",model);
} //获取创建表单页面
@GetMapping("/form")
public ModelAndView createForm(Model model){
model.addAttribute("user",new User());
model.addAttribute("title","创建用户");
return new ModelAndView("user/form","userModel",model);
} //保存用户
@PostMapping
public ModelAndView saveOrUpdateUser(User user){
user =userRepository.saveOrUpdateUser(user);
return new ModelAndView("redirect:/user/userlist");
} //根据id删除用户
@GetMapping(value = "delete/{id}")
public ModelAndView delete(@PathVariable("id") Long id){
userRepository.deleteUsere(id);
return new ModelAndView("redirect:/user/userlist");
} //修改用户界面
@GetMapping(value = "edit/{id}")
public ModelAndView editForm(@PathVariable("id") Long id, Model model){
User user =userRepository.getUserById(id);
model.addAttribute("user",user);
model.addAttribute("title","编辑用户");
return new ModelAndView("user/form" ,"userModel",model);
}
}

UserController

  具体说说,无论是新增用户保存后还是删除用户后都应该跳转回用户列表展示界面,之前代码用的“redirect”,根据别人评论我改成了

"redirect:/user/userlist",但是也没有去验证之前的写法对不对
    //保存用户
@PostMapping
public ModelAndView saveOrUpdateUser(User user){
user =userRepository.saveOrUpdateUser(user);
return new ModelAndView("redirect:/user/userlist");
} //根据id删除用户
@GetMapping(value = "delete/{id}")
public ModelAndView delete(@PathVariable("id") Long id){
userRepository.deleteUsere(id);
return new ModelAndView("redirect:/user/userlist");
}

运行:运行主程序DemoApplication.java,根据输出所示的端口访问界面,端口一般是8080,则访问http://127.0.0.1:8080/user/userlist

springBoot学习(一):初学Thymeleaf的更多相关文章

  1. springboot学习日志(二)-- thymeleaf学习

    本次学习如何使用thymeleaf以及相关语法1.在上一章写的那样 引入jar包到maven工程 <dependency> <groupId>org.springframewo ...

  2. Spring Boot学习记录(二)--thymeleaf模板 - CSDN博客

    ==他的博客应该不错,没有细看 Spring Boot学习记录(二)--thymeleaf模板 - CSDN博客 http://blog.csdn.net/u012706811/article/det ...

  3. 尚硅谷springboot学习14-自动配置原理

    配置文件能配置哪些属性 配置文件能配置的属性参照 自动配置的原理 1).SpringBoot启动的时候加载主配置类,开启了自动配置功能 @EnableAutoConfiguration 2).@Ena ...

  4. Springboot学习03-SpringMVC自动配置

    Springboot学习03-SpringMVC自动配置 前言 在SpringBoot官网对于SpringMVCde 自动配置介绍 1-原文介绍如下: Spring MVC Auto-configur ...

  5. SpringBoot学习笔记(2):引入Spring Security

    SpringBoot学习笔记(2):用Spring Security来保护你的应用 快速开始 本指南将引导您完成使用受Spring Security保护的资源创建简单Web应用程序的过程. 参考资料: ...

  6. springboot 学习资源推荐

    springboot 是什么?对于构建生产就绪的Spring应用程序有一个看法. Spring Boot优先于配置的惯例,旨在让您尽快启动和运行.(这是springboot的官方介绍) 我们为什么要学 ...

  7. Springboot学习记录1--概念介绍以及环境搭建

    摘要:springboot学习记录,环境搭建: 官方文档地址:https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/ht ...

  8. SpringBoot学习笔记

    SpringBoot个人感觉比SpringMVC还要好用的一个框架,很多注解配置可以非常灵活的在代码中运用起来: springBoot学习笔记: .一.aop: 新建一个类HttpAspect,类上添 ...

  9. springboot学习(一)——helloworld

    以下内容,如有问题,烦请指出,谢谢 springboot出来也很久了,以前零散地学习了不少,不过很长时间了都没有在实际中使用过了,忘了不少,因此要最近准备抽时间系统的学习积累下springboot,给 ...

  10. SpringBoot整合Jsp和Thymeleaf (附工程)

    前言 本篇文章主要讲述SpringBoot整合Jsp以及SpringBoot整合Thymeleaf,实现一个简单的用户增删改查示例工程.事先说明,有三个项目,两个是单独整合的,一个是将它们整合在一起的 ...

随机推荐

  1. 使用swap扩展内存

    当系统在内存不够用的时,新建一个swap文件,这个文件可以把内存中暂时不用的传输到对应的swap文件上,相当于扩展了内存的大小,具体使用方法如下: swap文件可以自己选择放在哪里,自己新建一个对应的 ...

  2. FICO-错误日志集

    1.F-02报错 System error in routine FI_TAX_CHK_PRICING_DATA error code 13 function builder TAX2 程序 FI_T ...

  3. 如何避免Linux操作系统客户端登陆超时-linux命令之TMOUT=

    工作中经常遇到使用ssh,telnet工具登陆Linux操作系统时,出现的超时问题,怎么处理呢? 添加下面命令: TMOUNT=

  4. SVN上传本地项目到服务器

    1. 在服务器新建一个文件夹目录: 2. 将新建的目录在本地check out下来: 3. 将自己的项目拷贝到check out下来的文件夹下: 4. 右键点击svnàAdd,选择所有添加: 5. 右 ...

  5. lumen中安装及使用redis作为cache

      1.安装redis模块在compose.json的require中添加 "predis/predis": "*","illuminate/redi ...

  6. redo log和bin log

    讲redolog和binlog之前,先要讲一下一条mysql语句的执行过程. 1.client的写请求到达连接器,连接器负责管理连接.验证权限: 2.然后是分析器,负责复习语法,如果这条语句有执行过, ...

  7. Servlet快速入门:第一个Servlet程序

    Servlet是整个JavaWeb开发的核心,同时也是一套规范,即公共接口.用于处理客户端发来的请求并作出响应.通常情况下我们会发送不同的请求并交由不同的处理程序来处理,例如处理用户信息和处理订单信息 ...

  8. Computer Vision_33_SIFT:TILDE: A Temporally Invariant Learned DEtector——2014

    此部分是计算机视觉部分,主要侧重在底层特征提取,视频分析,跟踪,目标检测和识别方面等方面.对于自己不太熟悉的领域比如摄像机标定和立体视觉,仅仅列出上google上引用次数比较多的文献.有一些刚刚出版的 ...

  9. c# 调试过程

  10. [Docker][ansible-playbook]3 持续集成环境之分布式部署

    预计阅读时间: 30分钟 本期解决痛点如下:1. 代码版本的多样性,编译环境的多样性如何解决?答案是使用docker,将不同的编译环境images统统打包到私有仓库上,根据需求进行下载,从宿主机上挂载 ...