Thymeleaf+springBoot实现:“增”,“删”,“改”,“查”接口功能(1)
1.增
前台代码:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div th:replace="~{fragments/header :: header}"></div>
<h3 th:text="${userModel.title}">tianzhen</h3>
<form action="/user" th:action="@{/user}" method="post" th:object="${userModel.user}">
<input type="hidden" name="id" th:value="*{id}">
名称:
<input type="text" name="name" th:value="*{name}"><br>
邮箱:
<input type="text" name="email" th:value="*{email}"><br>
<input type="submit" name="提交"><br>
</form>
<div th:replace="~{fragments/footer :: footer}"></div>
</body>
</html>
后台代码:
1.controller中
/**
* 创建
*
* @return
*/
@PostMapping
public ModelAndView saveOrUpdateUser(User user) {
user = userRepository.saveOrUpdateUser(user);
return new ModelAndView("redirect:/user/list");// 重定向到list页面
}
2.实现类中
// 每个用户有一个唯一id:计数器
private static AtomicLong counter = new AtomicLong();
// 存储到内存中
private final ConcurrentMap<Long, User> userMap = new ConcurrentHashMap<>();
/**
* @param user
* @return
* @author lenovo Sep 29, 2018 10:43:04 AM
* @version 1.0
*/
@Override
public User saveOrUpdateUser(User user) {
Long id = user.getId();
if (id == null) {
id = counter.incrementAndGet();
user.setId(id);
}
this.userMap.put(id, user);
return user;
}
3.页面