SpringBoot整合Thymeleaf小项目及详细流程

网友投稿 351 2022-08-18


SpringBoot整合Thymeleaf小项目及详细流程

目录1.项目简绍2.设计流程3.项目展示4.主要代码1.验证码的生成2.userController的控制层设计3.employeeController控制层的代码4.前端控制配置类5.过滤器6.yml配置7.文章添加页面展示8.POM.xml配置类9.employeeMapper配置类10.UserMapper配置类

1.项目简绍

本项目使用SpringBoot开发,jdbc5.1.48 Mybatis 源码可下载

其中涉及功能有:Mybatis的使用,Thymeleaf的使用,用户密码加密,验证码的设计,图片的文件上传(本文件上传到本地,没有传到数据库)登录过滤等

用户数据库

员工数据库设计

基本的增删改查都有

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开发,jdbc5.1.48

### 1.数据库信息

创建两个表,管理员表user和员工表employee

### 2.项目流程

1.springboot集成thymeleaf

1).引入依赖

org.springframework.boot

spring-boot-starter-thymeleaf

2).配置thymeleaf模板配置

spring:

thymeleaf:

cache: false # 关闭缓存

prefix: classpath:/templates/ #指定模板位置

suffix: .html #指定后缀

3).开发controller跳转到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的头才能使用相关语法

namespace: 命名空间

2).在html中通过thymeleaf语法获取数据

================================================================

###3.案例开发流程

需求分析: 分析这个项目含有哪些功能模块

用户模块:

注册

登录

验证码

安全退出

真是用户

员工模块:

添加员工+上传头像

展示员工列表+展示员工头像

删除员工信息+删除员工头像

更新员工信息+更新员工头像

库表设计(概要设计): 1.分析系统有哪些表 2.分析表与表关系 3.确定表中字段(显性字段 隐性字段(业务字段))

2张表

1.用户表 user

id username realname password gender

2.员工表 employee

id name salary birthday photo

创建一个库: ems-thymeleaf

详细设计:

省略

编码(环境搭建+业务代码开发)

1.创建一个springboot项目 项目名字: ems-thymeleaf

2.修改配置文件为 application.yml pom.xml 2.5.0

3.修改端口 项目名: ems-thymeleaf

4.springboot整合thymeleaf使用

a.引入依赖

b.配置文件中指定thymeleaf相关配置

c.编写控制器测试

5.springboot整合mybatis

mysql、druid、mybatis-springboot-stater

b.配置文件中

6.导入项目页面

static 存放静态资源

templates 目录 存放模板文件

测试

上线部署

维护

发版

======================================================================

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字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符

public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";

private static Random random = new Random();

/**

* 使用系统默认字符源生成验证码

* @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 {

//随机生成四位随机数

String code = VerifyCodeUtils.generateVerifyCode(4);

//保存到session域中

session.setAttribute("code",code);

//根据随机数生成图片,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"; //注册成功跳转到登录页面

/**

* 用户登录

@RequestMapping(value = "login")

public String login(String username,String password,HttpSession session){

log.info("本次登录用户名:{}",username);

log.info("本次登录密码:{}",password);

try {

//调用业务层进行登录

User user = userService.login(username, password);

//保存Session信息

session.setAttribute("user",user);

} catch (Exception e) {

return "redirect:/login";//登录失败回到登录页面

return "redirect:/employee/lists";//登录成功跳转到查询页面

//退出

@RequestMapping(value = "/logout")

public String logout(HttpSession session) {

session.invalidate();//session失效

return "redirect:/login";//跳转到登录页面

}

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 employeeList = employeeService.lists();

model.addAttribute("employeeList",employeeList);

return "emplist";

/**

* 根据id查询员工详细信息

*

* @param id

* @param model

* @return

*/

@RequestMapping(value = "/detail")

public String detail(Integer id, Model model) {

log.debug("当前查询员工id: {}", id);

//1.根据id查询一个

Employee employee = employeeService.findById(id);

model.addAttribute("employee", employee);

return "updateEmp";//跳转到更新页面

//上传头像方法

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";//保存成功跳转到列表页面

* 更新员工信息

* @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.删除老的头像 根据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/lisZHYGCVYBts";//更新成功,跳转到员工列表

* 删除员工信息

@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";//跳转到员工列表

}

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", "没有权限请先登录");

request.getRequestDispatcher("/login.html").forward(request, response);

return false;

} else {

return true;

}

}

}

6.yml配置

#关闭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\photo

7.文章添加页面展示

href="css/style.css" />

2022/03/21


main

添加员工信息:

class="form_table">

姓名:

头像:

工资:

生日:

1375595011@qq.com

8.POM.xml配置类

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.6.4

com.xuda.springboot

010-springboot-ems-thymeleaf

1.0.0

010-springboot-ems-thymeleaf

Demo project for Spring Boot

1.8

mysql

mysql-connector-java

5.1.48

org.springframework.boot

spring-boot-starter-thymeleaf

spring-boot-starter-web

org.mybatis.spring.boot

mybatis-spring-boot-starter

2.2.2

org.projectlombok

lombok

true

spring-boot-starter-test

test

com.alibaba

druid

1.1.10

org.springframework.boot

spring-boot-maven-plugin

org.projectlombok

lombok

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

org.springframework.boot

spring-boot-starter-parent

2.6.4

com.xuda.springboot

010-springboot-ems-thymeleaf

1.0.0

010-springboot-ems-thymeleaf

Demo project for Spring Boot

1.8

mysql

mysql-connector-java

5.1.48

org.springframework.boot

spring-boot-starter-thymeleaf

spring-boot-starter-web

org.mybatis.spring.boot

mybatis-spring-boot-starter

2.2.2

org.projectlombok

lombok

true

spring-boot-starter-test

test

com.alibaba

druid

1.1.10

org.springframework.boot

spring-boot-maven-plugin

org.projectlombok

lombok

9.employeeMapper配置类

PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

select id,names,salary,birthday,photo from employee;

insert into `employee` values (#{id},#{names},#{salary},#{birthday},#{photo})

select id,names,salary,birthday,photo from employee

where id = #{id}

update `employee`

names=#{names},

salary=#{salary},

birthday=#{birthday},

names=#{photo},

delete from `employee` where id = #{id}

10.UserMapper配置类

PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

select id,username,realname,password,gender from user where username = #{username};

insert into USER values (#{id},#{username},#{realname},#{password},#{gender});

5.项目下载gitee


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:SpringBoot整合Keycloak实现单点登录的示例代码
下一篇:Flink入门级应用域名处理示例
相关文章

 发表评论

暂时没有评论,来抢沙发吧~