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的使用,用户密码加密,验证码的设计,图片的文件上传(本文件上传到本地,没有传到数据库)登录过滤等
用户数据库
SpringBoot整合Thymeleaf小项目及详细流程
文章图片

员工数据库设计
SpringBoot整合Thymeleaf小项目及详细流程
文章图片

基本的增删改查都有

2.设计流程
# Getting Started### Reference DocumentationFor 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)### GuidesThe 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.bootspring-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.用户表 userid username realname password gender2.员工表 employeeid name salary birthdayphoto创建一个库: ems-thymeleaf 详细设计:省略 编码(环境搭建+业务代码开发)1.创建一个springboot项目 项目名字: ems-thymeleaf2.修改配置文件为 application.ymlpom.xml2.5.03.修改端口项目名: ems-thymeleaf4.springboot整合thymeleaf使用a.引入依赖b.配置文件中指定thymeleaf相关配置c.编写控制器测试5.springboot整合mybatismysql、druid、mybatis-springboot-staterb.配置文件中 6.导入项目页面static存放静态资源templates 目录 存放模板文件 测试 上线部署 维护 发版======================================================================


3.项目展示 SpringBoot整合Thymeleaf小项目及详细流程
文章图片


SpringBoot整合Thymeleaf小项目及详细流程
文章图片

SpringBoot整合Thymeleaf小项目及详细流程
文章图片

SpringBoot整合Thymeleaf小项目及详细流程
文章图片


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 IOExceptionpublic 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 ospublic static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{outputImage(w, h, os, verifyCode); * 生成指定验证码图像文件* @param codepublic 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 = "https://www.it610.com/article/user")public class UserController {//日志private static final Logger log = LoggerFactory.getLogger(UserController.class); private UserService userService; @Autowiredpublic UserController(UserService userService) {this.userService = userService; }@RequestMapping(value = "https://www.it610.com/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 = "https://www.it610.com/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 = "https://www.it610.com/article/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 = "https://www.it610.com/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 = "https://www.it610.com/article/employee")public class EmployeeController {//打印日志private static final Logger log = LoggerFactory.getLogger(EmployeeController.class); @Value("${photo.file.dir}")private String realpath; private EmployeeService employeeService; @Autowiredpublic EmployeeController(EmployeeService employeeService) {this.employeeService = employeeService; }//查询信息@RequestMapping(value = "https://www.it610.com/lists")publicString lists(Model model){log.info("查询所有员工信息"); List employeeList = employeeService.lists(); model.addAttribute("employeeList",employeeList); return "emplist"; /*** 根据id查询员工详细信息** @param id* @param model* @return*/@RequestMapping(value = "https://www.it610.com/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.表单提交方式必须是post2.表单enctype属性必须为 multipart/form-data@RequestMapping(value = "https://www.it610.com/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 = "https://www.it610.com/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/lists"; //更新成功,跳转到员工列表* 删除员工信息@RequestMapping(value = "https://www.it610.com/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 */@Configurationpublic class MvcConfig implements WebMvcConfigurer {@Overridepublic 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 */@Configurationpublic class LoginHandlerInterceptor implements HandlerInterceptor {private static final Logger log = LoggerFactory.getLogger(LoginHandlerInterceptor.class); @Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {log.info("session+=》{}",request.getSession().getAttribute("user")); //登录成功后,应该有用户得sessionObject 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: falseprefix: classpath:/templates/ #指定模板位置suffix: .html #指定后缀名datasource:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/ssmbuild?characterEncoding=UTF-8username: rootpassword:web:resources:static-locations: classpath:/static/,file:${photo.file.dir} #暴露哪些资源可以通过项目名访问mybatis:mapper-locations: classpath:mapper/*.xmltype-aliases-package: com.xuda.springboot.pojo#Mybatis配置#日志配置logging:level:root: infocom.xuda: debug#指定文件上传的位置photo:file:dir: E:\IDEA_Project\SpringBoot_Demo_Plus\IDEA-SpringBoot-projectes\010-springboot-ems-thymeleaf\photo


7.文章添加页面展示
添加员工信息 2022/03/21

main
添加员工信息:
头像:工资:生日:
姓名:
1375595011@qq.com


8.POM.xml配置类
4.0.0org.springframework.bootspring-boot-starter-parent2.6.4 com.xuda.springboot010-springboot-ems-thymeleaf1.0.0010-springboot-ems-thymeleafDemo project for Spring Boot1.8mysqlmysql-connector-java5.1.48org.springframework.bootspring-boot-starter-thymeleafspring-boot-starter-weborg.mybatis.spring.bootmybatis-spring-boot-starter2.2.2org.projectlomboklomboktruespring-boot-starter-testtestcom.alibabadruid1.1.10org.springframework.bootspring-boot-maven-pluginorg.projectlomboklombok


9.employeeMapper配置类
select id,names,salary,birthday,photo from employee; insert into `employee` values (#{id},#{names},#{salary},#{birthday},#{photo})select id,names,salary,birthday,photo from employeewhere id = #{id}update `employee` names=#{names},salary=#{salary},birthday=#{birthday},names=#{photo},delete from `employee` where id = #{id}


10.UserMapper配置类
select id,username,realname,password,gender from user where username = #{username}; insert into USERvalues (#{id},#{username},#{realname},#{password},#{gender});

5.项目下载gitee
【SpringBoot整合Thymeleaf小项目及详细流程】到此这篇关于SpringBoot整合Thymeleaf小项目的文章就介绍到这了,更多相关SpringBoot整合Thymeleaf内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读