Thymeleaf是适用于Web和独立环境的现代服务器端Java模板引擎,能够处理HTML,XML,JavaScript,CSS甚至纯文本。
1.pom.xml添加thymeleaf依赖
<!--Thymeleaf模版引擎 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.application-dev.yml添加配置如下:
spring:
thymeleaf:
#模板的模式,支持 HTML, XML TEXT JAVASCRIPT
mode: HTML5
#编码 可不用配置
encoding: UTF-8
#内容类别,可不用配置
content-type: text/html
#开发配置为false,避免修改模板还要重启服务器
cache: false
#配置模板路径,默认是templates,可以不用配置
prefix: classpath:/templates
3.添加后端类
UserController类
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserServiceImpl userService;
/**
* 显示添加用户表单
*/
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String addUserForm(ModelMap map) {
map.addAttribute("title", "添加用户");
map.addAttribute("action", "add");
map.addAttribute("user", new User());
return "user/userForm";
}
/**
* 添加用户
*/
@PostMapping("/add")
public String addUser(User user){
userService.addUser(user);
return "redirect:/user/getUserList";
}
/**
* 显示更新用户表单
*/
@RequestMapping("update/{id}")
public String updateUser(@PathVariable int id,ModelMap map){
map.addAttribute("title", "更新用户");
map.addAttribute("action", "update");
map.addAttribute("user", userService.findUser(id));
return "user/userForm";
}
/**
* 更新用户
*/
@PostMapping("/update")
public String updateUser(User user){
userService.updateUser(user);
return "redirect:/user/getUserList";
}
/**
* 删除用户
*/
@RequestMapping("delete/{id}")
public String deleteUser(@PathVariable int id){
userService.deleteUser(id);
return "redirect:/user/getUserList";
}
/**
* 获取用户
*/
@RequestMapping("getUser/{id}")
public String getUser(ModelMap map,@PathVariable int id){
map.addAttribute("name","haozz");
map.addAttribute("userList",userService.findUser(id));
return "user/userList";
}
/**
* 获取用户列表
*/
@RequestMapping("/getUserList")
public ModelAndView getUserList(@RequestParam(name = "pageNum", required = false, defaultValue = "1") int pageNum,
@RequestParam(name = "pageSize", required = false, defaultValue = "10") int pageSize) {
ModelAndView model = new ModelAndView();
model.addObject("title", "用户列表");
model.addObject("userList", userService.findAllUser(pageNum,pageSize).getList());
model.setViewName("user/userList");
return model;
}
}
User类
package com.example.demo.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class User {
private Integer id;
private String userName;
private String passWord;
private String realName;
}
UserMapper类
package com.example.demo.mapper;
import com.example.demo.entity.User;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserMapper {
User selectUser(int id);
int insert(User record);
List<User> selectUsers();
int update(User user);
int deleteById(int id);
}
UserService接口
package com.example.demo.service;
import com.example.demo.entity.User;
import com.github.pagehelper.PageInfo;
public interface UserService {
int addUser(User user);
int updateUser(User user);
int deleteUser(int id);
User findUser(int id);
PageInfo<User> findAllUser(int pageNum, int pageSize);
}
UserServiceImpl实现类
package com.example.demo.service.impl;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserMapper userMapper;
@Override
public int addUser(User user) {
return userMapper.insert(user);
}
@Override
public int updateUser(User user) {
return userMapper.update(user);
}
@Override
public int deleteUser(int id) {
return userMapper.deleteById(id);
}
@Override
public User findUser(int id){
return userMapper.selectUser(id);
}
@Override
public PageInfo<User> findAllUser(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<User> userList = userMapper.selectUsers();
PageInfo result = new PageInfo(userList);
return result;
}
}
UserMapper.xml映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.demo.entity.User">
<result column="id" jdbcType="INTEGER" property="id" />
<result column="userName" jdbcType="VARCHAR" property="userName" />
<result column="passWord" jdbcType="VARCHAR" property="passWord" />
<result column="realName" jdbcType="VARCHAR" property="realName" />
</resultMap>
<sql id="BASE_TABLE">
user
</sql>
<sql id="BASE_COLUMN">
id,userName,passWord,realName
</sql>
<insert id="insert" parameterType="com.example.demo.entity.User">
INSERT INTO
<include refid="BASE_TABLE"/>
<trim prefix="(" suffix=")" suffixOverrides=",">
userName,passWord,
<if test="realName != null">
realName,
</if>
</trim>
<trim prefix="VALUES(" suffix=")" suffixOverrides=",">
#{userName, jdbcType=VARCHAR},#{passWord, jdbcType=VARCHAR},
<if test="realName != null">
#{realName, jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="update" parameterType="com.example.demo.entity.User">
UPDATE
<include refid="BASE_TABLE"/>
<set>
<if test="userName != null">
userName = #{userName, jdbcType=VARCHAR},
</if>
<if test="passWord != null">
passWord = #{passWord, jdbcType=VARCHAR},
</if>
<if test="realName != null">
realName = #{realName, jdbcType=VARCHAR},
</if>
</set>
WHERE id = #{id, jdbcType=INTEGER}
</update>
<update id="delete" parameterType="com.example.demo.entity.User">
DELETE FROM
<include refid="BASE_TABLE"/>
<set>
<if test="userName != null">
userName = #{userName, jdbcType=VARCHAR},
</if>
<if test="passWord != null">
passWord = #{passWord, jdbcType=VARCHAR},
</if>
<if test="realName != null">
realName = #{realName, jdbcType=VARCHAR},
</if>
</set>
WHERE id = #{id, jdbcType=INTEGER}
</update>
<delete id="deleteById" parameterType="java.lang.Integer">
delete from <include refid="BASE_TABLE"/>
where id = #{id,jdbcType=INTEGER}
</delete>
<select id="selectUser" resultType="com.example.demo.entity.User">
select * from user where id = #{id}
</select>
<select id="selectUsers" resultType="com.example.demo.entity.User">
SELECT
<include refid="BASE_COLUMN"/>
FROM
<include refid="BASE_TABLE"/>
</select>
</mapper>
4.templates添加user目录、userlist.html页面
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title th:text="${title}">Title</title>
</head>
<body>
<a href="/user/add" >添加</a></br>
<table class="table table-hover table-condensed">
<legend>
<strong>用户列表</strong>
</legend>
<thead>
<tr>
<th>用户编号</th>
<th>姓名</th>
<th>密码</th>
<th>真实姓名</th>
<th>管理</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${userList}">
<th scope="row" th:text="${user.id}"></th>
<td th:text="${user.userName}"></td>
<td>***</td>
<td th:text="${user.realName}"></td>
<td>
<a th:href="@{/user/update/{userId}(userId=${user.id})}" >更新</a>
<a class="btn btn-danger" th:href="@{/user/delete/{userId}(userId=${user.id})}">删除</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>
userForm.html页面
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title th:text="${title}">Title</title>
</head>
<body>
<form th:action="@{/user/{action}(action=${action})}" method="post" class="form-horizontal">
<input type="hidden" name="id" th:value="${user.id}"/>
<div class="form-group">
<label for="user_name" class="col-sm-2 control-label">姓名</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="user_name" name="userName" th:value="${user.userName}" />
</div>
</div>
<div class="form-group">
<label for="pass_word" class="col-sm-2 control-label">密码:</label>
<div class="col-xs-4">
<input type="password" class="form-control" id="pass_word" name="passWord" th:value="${user.passWord}"/>
</div>
</div>
<div class="form-group">
<label for="real_name" class="col-sm-2 control-label">真实姓名:</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="real_name" name="realName" th:value="${user.realName}"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input class="btn btn-primary" type="submit" value="提交"/>
<input class="btn" type="button" value="返回" onclick="history.back()"/>
</div>
</div>
</form>
</body>
</html>
5.浏览器访问http://localhost:8080/user/getUserList
这就实现了简单的crud功能。