SpringBoot整合Thymeleaf小項目及詳細流程
1.項目簡紹
本項目使用SpringBoot開發(fā),jdbc5.1.48 Mybatis 源碼可下載
其中涉及功能有:Mybatis的使用,Thymeleaf的使用,用戶密碼加密,驗證碼的設計,圖片的文件上傳(本文件上傳到本地,沒有傳到數(shù)據(jù)庫)登錄過濾等
用戶數(shù)據(jù)庫

員工數(shù)據(jù)庫設計

基本的增刪改查都有
2.設計流程
# Getting Started
### Reference Documentation
For further reference, please consider the following sections:
* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html)
* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/html/)
* [Create an OCI image](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/html/#build-image)
* [Spring Web](https://docs.spring.io/spring-boot/docs/2.6.4/reference/htmlsingle/#boot-features-developing-web-applications)
* [MyBatis Framework](https://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/)
* [JDBC API](https://docs.spring.io/spring-boot/docs/2.6.4/reference/htmlsingle/#boot-features-sql)
* [Thymeleaf](https://docs.spring.io/spring-boot/docs/2.6.4/reference/htmlsingle/#boot-features-spring-mvc-template-engines)
### Guides
The following guides illustrate how to use some features concretely:
* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/)
* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/)
* [Building REST services with Spring](https://spring.io/guides/tutorials/bookmarks/)
* [MyBatis Quick Start](https://github.com/mybatis/spring-boot-starter/wiki/Quick-Start)
* [Accessing Relational Data using JDBC with Spring](https://spring.io/guides/gs/relational-data-access/)
* [Managing Transactions](https://spring.io/guides/gs/managing-transactions/)
* [Handling Form Submission](https://spring.io/guides/gs/handling-form-submission/)
## 項目說明
本項目使用SpringBoot開發(fā),jdbc5.1.48
### 1.數(shù)據(jù)庫信息
創(chuàng)建兩個表,管理員表user和員工表employee
### 2.項目流程
1.springboot集成thymeleaf
1).引入依賴
<!--使用thymelaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2).配置thymeleaf模板配置
spring:
thymeleaf:
cache: false # 關(guān)閉緩存
prefix: classpath:/templates/ #指定模板位置
suffix: .html #指定后綴
3).開發(fā)controller跳轉(zhuǎn)到thymeleaf模板
@Controller
@RequestMapping("hello")
public class HelloController {
@RequestMapping("hello")
public String hello(){
System.out.println("hello ok");
return "index"; // templates/index.html
}
}
=================================================================
2.thymeleaf 語法使用
1).html使用thymeleaf語法 必須導入thymeleaf的頭才能使用相關(guān)語法
namespace: 命名空間
<html lang="en" xmlns:th="http://www.thymeleaf.org">
2).在html中通過thymeleaf語法獲取數(shù)據(jù)
================================================================
###3.案例開發(fā)流程
?
需求分析: 分析這個項目含有哪些功能模塊
用戶模塊:
注冊
登錄
驗證碼
安全退出
真是用戶
員工模塊:
添加員工+上傳頭像
展示員工列表+展示員工頭像
刪除員工信息+刪除員工頭像
更新員工信息+更新員工頭像
庫表設計(概要設計): 1.分析系統(tǒng)有哪些表 2.分析表與表關(guān)系 3.確定表中字段(顯性字段 隱性字段(業(yè)務字段))
2張表
1.用戶表 user
id username realname password gender
2.員工表 employee
id name salary birthday photo
創(chuàng)建一個庫: ems-thymeleaf
詳細設計:
省略
編碼(環(huán)境搭建+業(yè)務代碼開發(fā))
1.創(chuàng)建一個springboot項目 項目名字: ems-thymeleaf
2.修改配置文件為 application.yml pom.xml 2.5.0
3.修改端口 項目名: ems-thymeleaf
4.springboot整合thymeleaf使用
a.引入依賴
b.配置文件中指定thymeleaf相關(guān)配置
c.編寫控制器測試
5.springboot整合mybatis
mysql、druid、mybatis-springboot-stater
b.配置文件中
6.導入項目頁面
static 存放靜態(tài)資源
templates 目錄 存放模板文件
測試
上線部署
維護
發(fā)版
======================================================================3.項目展示




4.主要代碼
1.驗證碼的生成
package com.xuda.springboot.utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;
/**
* @author :程序員徐大大
* @description:TODO
* @date :2022-03-20 19:42
*/
public class VerifyCodeUtils {
//使用到Algerian字體,系統(tǒng)里沒有的話需要安裝字體,字體只顯示大寫,去掉了1,0,i,o幾個容易混淆的字符
public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
private static Random random = new Random();
/**
* 使用系統(tǒng)默認字符源生成驗證碼
* @param verifySize 驗證碼長度
* @return
*/
public static String generateVerifyCode(int verifySize){
return generateVerifyCode(verifySize, VERIFY_CODES);
}
* 使用指定源生成驗證碼
* @param sources 驗證碼字符源
public static String generateVerifyCode(int verifySize, String sources){
if(sources == null || sources.length() == 0){
sources = VERIFY_CODES;
}
int codesLen = sources.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(verifySize);
for(int i = 0; i < verifySize; i++){
verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
return verifyCode.toString();
* 生成隨機驗證碼文件,并返回驗證碼值
* @param w
* @param h
* @param outputFile
* @param verifySize
* @throws IOException
public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, outputFile, verifyCode);
return verifyCode;
* 輸出隨機驗證碼圖片流,并返回驗證碼值
* @param os
public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
outputImage(w, h, os, verifyCode);
* 生成指定驗證碼圖像文件
* @param code
public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
if(outputFile == null){
return;
File dir = outputFile.getParentFile();
if(!dir.exists()){
dir.mkdirs();
try{
outputFile.createNewFile();
FileOutputStream fos = new FileOutputStream(outputFile);
outputImage(w, h, fos, code);
fos.close();
} catch(IOException e){
throw e;
* 輸出指定驗證碼圖片流
public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Random rand = new Random();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
Color.PINK, Color.YELLOW };
float[] fractions = new float[colors.length];
for(int i = 0; i < colors.length; i++){
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
Arrays.sort(fractions);
g2.setColor(Color.GRAY);// 設置邊框色
g2.fillRect(0, 0, w, h);
Color c = getRandColor(200, 250);
g2.setColor(c);// 設置背景色
g2.fillRect(0, 2, w, h-4);
//繪制干擾線
Random random = new Random();
g2.setColor(getRandColor(160, 200));// 設置線條的顏色
for (int i = 0; i < 20; i++) {
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
// 添加噪點
float yawpRate = 0.05f;// 噪聲率
int area = (int) (yawpRate * w * h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
shear(g2, w, h, c);// 使圖片扭曲
g2.setColor(getRandColor(100, 160));
int fontSize = h-4;
Font font = new Font("Algerian", Font.ITALIC, fontSize);
g2.setFont(font);
char[] chars = code.toCharArray();
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
g2.setTransform(affine);
g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
g2.dispose();
ImageIO.write(image, "jpg", os);
private static Color getRandColor(int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
return color;
private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
return rgb;
private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10; // 50;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
g.copyArea(i, 0, 1, h1, 0, (int) d);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}2.userController的控制層設計
package com.xuda.springboot.controller;
import com.xuda.springboot.pojo.User;
import com.xuda.springboot.service.UserService;
import com.xuda.springboot.utils.VerifyCodeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* @author :程序員徐大大
* @description:TODO
* @date :2022-03-20 20:06
*/
@Controller
@RequestMapping(value = "user")
public class UserController {
//日志
private static final Logger log = LoggerFactory.getLogger(UserController.class);
private UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@RequestMapping(value = "/generateImageCode")
public void generateImageCode(HttpSession session,HttpServletResponse response) throws IOException {
//隨機生成四位隨機數(shù)
String code = VerifyCodeUtils.generateVerifyCode(4);
//保存到session域中
session.setAttribute("code",code);
//根據(jù)隨機數(shù)生成圖片,reqponse響應圖片
response.setContentType("image/png");
ServletOutputStream os = response.getOutputStream();
VerifyCodeUtils.outputImage(130,60,os,code);
/*
用戶注冊
*/
@RequestMapping(value = "/register")
public String register(User user, String code, HttpSession session, Model model){
log.debug("用戶名:{},真實姓名:{},密碼:{},性別:{},",user.getUsername(),user.getRealname(),user.getPassword(),user.getGender());
log.debug("用戶輸入的驗證碼:{}",code);
try{
//判斷用戶輸入驗證碼和session中的驗證碼是否一樣
String sessioncode = session.getAttribute("code").toString();
if(!sessioncode.equalsIgnoreCase(code)) {
throw new RuntimeException("驗證碼輸入錯誤");
}
//注冊用戶
userService.register(user);
}catch (RuntimeException e){
e.printStackTrace();
return "redirect:/register";//注冊失敗返回注冊頁面
}
return "redirect:/login"; //注冊成功跳轉(zhuǎn)到登錄頁面
/**
* 用戶登錄
@RequestMapping(value = "login")
public String login(String username,String password,HttpSession session){
log.info("本次登錄用戶名:{}",username);
log.info("本次登錄密碼:{}",password);
try {
//調(diào)用業(yè)務層進行登錄
User user = userService.login(username, password);
//保存Session信息
session.setAttribute("user",user);
} catch (Exception e) {
return "redirect:/login";//登錄失敗回到登錄頁面
return "redirect:/employee/lists";//登錄成功跳轉(zhuǎn)到查詢頁面
//退出
@RequestMapping(value = "/logout")
public String logout(HttpSession session) {
session.invalidate();//session失效
return "redirect:/login";//跳轉(zhuǎn)到登錄頁面
}3.employeeController控制層的代碼
package com.xuda.springboot.controller;
import com.xuda.springboot.pojo.Employee;
import com.xuda.springboot.service.EmployeeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* @author :程序員徐大大
* @description:TODO
* @date :2022-03-21 13:44
*/
@Controller
@RequestMapping(value = "employee")
public class EmployeeController {
//打印日志
private static final Logger log = LoggerFactory.getLogger(EmployeeController.class);
@Value("${photo.file.dir}")
private String realpath;
private EmployeeService employeeService;
@Autowired
public EmployeeController(EmployeeService employeeService) {
this.employeeService = employeeService;
}
//查詢信息
@RequestMapping(value = "/lists")
public String lists(Model model){
log.info("查詢所有員工信息");
List<Employee> employeeList = employeeService.lists();
model.addAttribute("employeeList",employeeList);
return "emplist";
/**
* 根據(jù)id查詢員工詳細信息
*
* @param id
* @param model
* @return
*/
@RequestMapping(value = "/detail")
public String detail(Integer id, Model model) {
log.debug("當前查詢員工id: {}", id);
//1.根據(jù)id查詢一個
Employee employee = employeeService.findById(id);
model.addAttribute("employee", employee);
return "updateEmp";//跳轉(zhuǎn)到更新頁面
//上傳頭像方法
private String uploadPhoto(MultipartFile img, String originalFilename) throws IOException {
String fileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
String fileNameSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
String newFileName = fileNamePrefix + fileNameSuffix;
img.transferTo(new File(realpath, newFileName));
return newFileName;
* 保存員工信息
* 文件上傳: 1.表單提交方式必須是post 2.表單enctype屬性必須為 multipart/form-data
@RequestMapping(value = "/save")
public String save(Employee employee, MultipartFile img) throws IOException {
log.debug("姓名:{}, 薪資:{}, 生日:{} ", employee.getNames(), employee.getSalary(), employee.getBirthday());
String originalFilename = img.getOriginalFilename();
log.debug("頭像名稱: {}", originalFilename);
log.debug("頭像大小: {}", img.getSize());
log.debug("上傳的路徑: {}", realpath);
log.debug("第一次--》員工信息:{}",employee.getNames());
//1.處理頭像的上傳&修改文件名稱
String newFileName = uploadPhoto(img, originalFilename);
//2.保存員工信息
employee.setPhoto(newFileName);//保存頭像名字
employeeService.save(employee);
return "redirect:/employee/lists";//保存成功跳轉(zhuǎn)到列表頁面
* 更新員工信息
* @param employee
* @param img
@RequestMapping(value = "/update")
public String update(Employee employee, MultipartFile img) throws IOException {
log.debug("更新之后員工信息: id:{},姓名:{},工資:{},生日:{},", employee.getId(), employee.getNames(), employee.getSalary(), employee.getBirthday());
//1.判斷是否更新頭像
boolean notEmpty = !img.isEmpty();
log.debug("是否更新頭像: {}", notEmpty);
if (notEmpty) {
//1.刪除老的頭像 根據(jù)id查詢原始頭像
String oldPhoto = employeeService.findById(employee.getId()).getPhoto();
File file = new File(realpath, oldPhoto);
if (file.exists()) file.delete();//刪除文件
//2.處理新的頭像上傳
String originalFilename = img.getOriginalFilename();
String newFileName = uploadPhoto(img, originalFilename);
//3.修改員工新的頭像名稱
employee.setPhoto(newFileName);
}
//2.沒有更新頭像直接更新基本信息
employeeService.update(employee);
return "redirect:/employee/lists";//更新成功,跳轉(zhuǎn)到員工列表
* 刪除員工信息
@RequestMapping(value = "/delete")
public String delete(Integer id){
log.debug("刪除的員工id: {}",id);
String photo = employeeService.findById(id).getPhoto();
employeeService.delete(id);
//2.刪除頭像
File file = new File(realpath, photo);
if (file.exists()) file.delete();
return "redirect:/employee/lists";//跳轉(zhuǎn)到員工列表
}4.前端控制配置類
package com.xuda.springboot.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author :程序員徐大大
* @description:TODO
* @date :2022-03-20 20:49
*/
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("redirect:/login");
registry.addViewController("login").setViewName("login");
registry.addViewController("login.html").setViewName("login");
registry.addViewController("register").setViewName("regist");
registry.addViewController("addEmp").setViewName("addEmp");
}
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/register","/user/login","/css/**","/js/**","/img/**","/user/register","/login","/login.html");
}5.過濾器
package com.xuda.springboot.config;
import com.xuda.springboot.controller.UserController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author :程序員徐大大
* @description:TODO
* @date :2022-03-21 20:17
*/
@Configuration
public class LoginHandlerInterceptor implements HandlerInterceptor {
private static final Logger log = LoggerFactory.getLogger(LoginHandlerInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("session+=》{}",request.getSession().getAttribute("user"));
//登錄成功后,應該有用戶得session
Object loginuser = request.getSession().getAttribute("user");
if (loginuser == null) {
request.setAttribute("loginmsg", "沒有權(quán)限請先登錄");
request.getRequestDispatcher("/login.html").forward(request, response);
return false;
} else {
return true;
}
}
}6.yml配置
#關(guān)閉thymeleaf模板緩存
spring:
thymeleaf:
cache: false
prefix: classpath:/templates/ #指定模板位置
suffix: .html #指定后綴名
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssmbuild?characterEncoding=UTF-8
username: root
password:
web:
resources:
static-locations: classpath:/static/,file:${photo.file.dir} #暴露哪些資源可以通過項目名訪問
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.xuda.springboot.pojo
#Mybatis配置
#日志配置
logging:
level:
root: info
com.xuda: debug
#指定文件上傳的位置
photo:
file:
dir: E:\IDEA_Project\SpringBoot_Demo_Plus\IDEA-SpringBoot-projectes\010-springboot-ems-thymeleaf\photo7.文章添加頁面展示
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:th="http://www.thymealf.org">
<head>
<title>添加員工信息</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css"
href="css/style.css" />
</head>
<body>
<div id="wrap">
<div id="top_content">
<div id="header">
<div id="rightheader">
<p>
2022/03/21
<br />
</p>
</div>
<div id="topheader">
<h1 id="title">
<a href="#">main</a>
</h1>
<div id="navigation">
</div>
<div id="content">
<p id="whereami">
</p>
<h1>
添加員工信息:
</h1>
<form th:action="@{/employee/save}" method="post" enctype="multipart/form-data">
<table cellpadding="0" cellspacing="0" border="0"
class="form_table">
<tr>
<td valign="middle" align="right">
姓名:
</td>
<td valign="middle" align="left">
<input type="text" class="inputgri" name="names" />
</tr>
頭像:
<input type="file" width="" name="img" />
工資:
<input type="text" class="inputgri" name="salary" />
生日:
<input type="text" class="inputgri" name="birthday" />
</table>
<input type="submit" class="button" value="確認添加" />
<input type="submit" class="button" value="返回列表" />
</form>
</div>
<div id="footer">
<div id="footer_bg">
1375595011@qq.com
</div>
</body>
</html>8.POM.xml配置類
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.xuda.springboot</groupId>
<artifactId>010-springboot-ems-thymeleaf</artifactId>
<version>1.0.0</version>
<name>010-springboot-ems-thymeleaf</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--jdbc驅(qū)動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
<!--thymeleaf啟動依賴-->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<!--springboot啟動依賴-->
<artifactId>spring-boot-starter-web</artifactId>
<!--mybatis整合springboot-->
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
<!--lombok-->
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<!--springboot測試啟動依賴-->
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>9.employeeMapper配置類
<?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.xuda.springboot.dao.EmployeeMapper">
<select id="lists" resultType="Employee">
select id,names,salary,birthday,photo from employee;
</select>
<!--<insert id="save" parameterType="User" useGeneratedKeys="true" keyProperty="id">
insert into USER values (#{id},#{username},#{realname},#{password},#{gender});
</insert>-->
<!--save-->
<insert id="save" parameterType="Employee" useGeneratedKeys="true" keyProperty="id">
insert into `employee` values (#{id},#{names},#{salary},#{birthday},#{photo})
</insert>
<!--findById-->
<select id="findById" parameterType="Integer" resultType="Employee">
select id,names,salary,birthday,photo from employee
where id = #{id}
<!--update-->
<update id="update" parameterType="Employee" >
update `employee` <set>
<if test="names != null">
names=#{names},
</if>
<if test="salary != null">
salary=#{salary},
</if>
<if test="birthday != null">
birthday=#{birthday},
<if test="photo != null">
names=#{photo},
</set>
</update>
<!--delete-->
<delete id="delete" parameterType="Integer">
delete from `employee` where id = #{id}
</delete>
</mapper>10.UserMapper配置類
<?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.xuda.springboot.dao.UserMapper">
<select id="findByUserName" parameterType="String" resultType="User">
select id,username,realname,password,gender from user where username = #{username};
</select>
<insert id="save" parameterType="User" useGeneratedKeys="true" keyProperty="id">
insert into USER values (#{id},#{username},#{realname},#{password},#{gender});
</insert>
</mapper>
5.項目下載gitee
到此這篇關(guān)于SpringBoot整合Thymeleaf小項目的文章就介紹到這了,更多相關(guān)SpringBoot整合Thymeleaf內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用JAXBContext輕松實現(xiàn)Java和xml的互相轉(zhuǎn)換方式
這篇文章主要介紹了依靠JAXBContext輕松實現(xiàn)Java和xml的互相轉(zhuǎn)換方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
Java連接SQL?Server數(shù)據(jù)庫的超詳細教程
在Java應用程序中我們經(jīng)常需要與數(shù)據(jù)庫進行交互,一種常見的數(shù)據(jù)庫是Microsoft?SQL?Server,下面這篇文章主要給大家介紹了關(guān)于Java連接SQL?Server數(shù)據(jù)庫的超詳細教程,需要的朋友可以參考下2024-01-01
SpringBoot嵌入式Servlet容器與定制化組件超詳細講解
這篇文章主要介紹了SpringBoot嵌入式Servlet容器與定制化組件的使用介紹,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2022-10-10

