springboot基础案例(二)

文章目录

  • 前言
  • 一.需求分析: 分析这个项目含有哪些功能模块
  • 二.库表设计(概要设计): 1.分析系统有哪些表 2.分析表与表关系 3.确定表中字段(显性字段 隐性字段(业务字段))
    • 2.1 创建一个库: ems-thymeleaf
    • 2.2 创建 2张表
    • 三.编码(环境搭建)
      • 1.创建一个springboot项目 项目名字: ems-thymeleaf
      • 2.修改配置文件为 application.yml pom.xml
      • 3.修改端口 9999 项目名: ems-thymeleaf
      • 4.springboot整合thymeleaf使用
      • 5.springboot整合mybatis
      • 6.导入项目页面
      • 7.配置thymeleaf模版controller统一请求
    • 四.编码(业务代码开发)
      • 1.验证码实现
      • 2.用户注册实现
      • 3.用户登录实现
      • 3.员工列表实现
      • 4.增加员工信息
      • 5.更新员工的实现
      • 6.删除员工的实现

前言

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

	用户模块:注册登录验证码安全退出真是用户员工模块:添加员工+上传头像展示员工列表+展示员工头像删除员工信息+删除员工头像更新员工信息+更新员工头像

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

2.1 创建一个库: ems-thymeleaf

2.2 创建 2张表

1.用户表 user
id username realname password gender

CREATE TABLE `employee` (`id` int(11) unsigned NOT NULL AUTO_INCREMENT,`name` varchar(60) DEFAULT NULL COMMENT '员工姓名',`salary` double(10,2) DEFAULT NULL COMMENT '员工工资',`birthday` datetime DEFAULT NULL COMMENT '员工生日',`photo` varchar(200) DEFAULT NULL COMMENT '头像路径',PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

2.员工表 employee
id name salary birthday photo

CREATE TABLE `user` (`id` int(11) unsigned NOT NULL AUTO_INCREMENT,`username` varchar(40) DEFAULT NULL COMMENT '用户名',`realname` varchar(60) DEFAULT NULL COMMENT '真实姓名',`password` varchar(40) DEFAULT NULL COMMENT '密码',`gender` tinyint(1) unsigned DEFAULT NULL COMMENT '性别',PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

三.编码(环境搭建)

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

在这里插入图片描述

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

修改poml版本为 springboot版本为2.7.14
在这里插入图片描述

把application.properties修改为application.yml
在这里插入图片描述

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

在这里插入图片描述

4.springboot整合thymeleaf使用

a.引入依赖

<!--		引入thymeleaf--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>

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

spring:thymeleaf:prefix: classpath:/templates/  #指定thymeleaf模板前缀目录suffix: .html                  #指定模板的后缀cache: false                    #是否开启thymeleaf缓存 默认值是true开启缓存  在开发过程中推荐使用false

c.编写控制器测试

@Controller
@RequestMapping("demo")
public class DemoController {private static final Logger log = LoggerFactory.getLogger(DemoController.class);@RequestMapping("demo")public String demo(Model model){log.debug("demo ok");model.addAttribute("msg","hello thymeleaf");return "demo";}}

d.最后访问
在这里插入图片描述

5.springboot整合mybatis

a.引入依赖
mysql、druid、mybatis-springboot-stater

<!--mysql--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.38</version></dependency><!--druid--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.4</version></dependency><!--myabtis-springboot--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.4</version></dependency>

b.配置文件

# 数据库的配置
# 数据库的配置datasource:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/ems-thymeleaf?characterEncoding=UTF-8username: rootpassword: 123456#配置mybatis
mybatis:mapper-locations: classpath:mapper/**Mapper.xmltype-aliases-package: com.demo.entity# 日志配置
logging:level:root: infocom.demo: debug

6.导入项目页面

static 存放静态资源
在这里插入图片描述

templates 目录 存放模板文件
在这里插入图片描述

7.配置thymeleaf模版controller统一请求

因为我们thymeleaf模板开发,要访问静态资源的时候,我们必须建controller请求,这样比较麻烦,我们可以统一配置,具体操作如下:

@Configuration
public class MvcConfig implements WebMvcConfigurer {通过这里面配置: 不需要为每一个访问thymeleaf模板页面单独开发一个controller请求了@Overridepublic void addViewControllers(ViewControllerRegistry registry) {//viewController 请求路径    viewName: 跳转视图registry.addViewController("login").setViewName("login");registry.addViewController("register").setViewName("regist");}
}

四.编码(业务代码开发)

1.验证码实现

在这里插入图片描述
Controller代码如下:

 @RequestMapping("generateImageCode")public void generateImageCode(HttpSession session, HttpServletResponse response) throws IOException {//1.生成4位随机数String code = VerifyCodeUtils.generateVerifyCode(4);//2.保存到session作用域session.setAttribute("code",code);//3.根据随机数生成图片 && 4.通过response响应图片  && 5.设置响应类型response.setContentType("image/png");ServletOutputStream os = response.getOutputStream();VerifyCodeUtils.outputImage(220,60, os,code);}
}

前端页面改的位置
在这里插入图片描述

2.用户注册实现

在这里插入图片描述
Controller

  @RequestMapping("register")public String register(User user, String code,HttpSession session){log.debug("用户名: {},真是姓名: {},密码: {},性别: {},",user.getUsername(),user.getRealname(),user.getPassword(),user.getGender());log.debug("用户输入验证码: {}",code);try {//1.判断用户输入验证码和session中验证码是否一致String sessionCode = session.getAttribute("code").toString();if(!sessionCode.equalsIgnoreCase(code))throw new RuntimeException("验证码输入错误!");//2.注册用户userService.register(user);} catch (RuntimeException e) {e.printStackTrace();return "redirect:/register"; //注册失败回到注册}return  "redirect:/login";  //注册成功跳转到登录}

实体类

public class User {private Integer id;private String username;private String realname;private String password;private Boolean gender;}

Service

public class UserService {/*** 注册用户*/private UserMapper userMapper;@Autowiredpublic UserService(UserMapper userMapper){this.userMapper=userMapper;}public void register(User user) {//1.根据用户名查询数据库中是否存在改用户User userDB = userMapper.findByUserName(user.getUsername());//2.判断用户是否存在if(!ObjectUtils.isEmpty(userDB)) throw new RuntimeException("当前用户名已被注册!");//3.注册用户&明文的密码加密  特点: 相同字符串多次使用md5就行加密 加密结果始终是一致String newPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8));user.setPassword(newPassword);userMapper.save(user);}
}

Mapper

    <!--findByUserName--><select id="findByUserName" parameterType="String" resultType="User">select id,username,realname,password,gender from `user`where username = #{username}</select><!--save--><insert id="save" parameterType="User" useGeneratedKeys="true" keyProperty="id">insert into `user` values(#{id},#{username},#{realname},#{password},#{gender})</insert>

3.用户登录实现

在这里插入图片描述
Controller

 @RequestMapping("login")public String login(String username,String password,HttpSession session){log.debug("本次登录用户名: {}",username);log.debug("本地登录密码: {}",password);try {//1.调用业务层进行登录User user = userService.login(username,password);//2.保存用户信息session.setAttribute("user",user);} catch (Exception e) {e.printStackTrace();return "redirect:/login";//登录失败回到登录界面}return "redirect:/employee/lists";//登录成功之后,跳转到查询所有员工信息控制器路径}

Service

 public User login(String username, String password) {//1.根据用户名查询用户User user = userMapper.findByUserName(username);if(ObjectUtils.isEmpty(user)) throw new RuntimeException("用户名不正确!");//2.比较密码String passwordSecret = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));if(!user.getPassword().equals(passwordSecret)) throw new RuntimeException("密码输入错误!");return user;}

Mapper

    <!--findByUserName--><select id="findByUserName" parameterType="String" resultType="User">select id,username,realname,password,gender from `user`where username = #{username}</select>

3.员工列表实现

在这里插入图片描述
实体类

public class Employee {private Integer id;private String name;private Double salary;private Date birthday;private String photo;//头像路径}

Controller

 @RequestMapping("lists")public String lists(Model model){log.debug("查询所有员工信息");List<Employee> employeeList=employeeService.lists();model.addAttribute("employeeList",employeeList);return "emplist";}

Service

public List<Employee> lists(){return employeeMapper.lists();}

Mapper

 <!--lists--><select id="lists" resultType="Employee">select id,name,salary,birthday,photo from `employee`</select>

4.增加员工信息

在这里插入图片描述

Controller

 @RequestMapping("save")public String save(Employee employee, MultipartFile img) throws IOException {log.debug("姓名:{}, 薪资:{}, 生日:{} ", employee.getName(), employee.getSalary(), employee.getBirthday());String originalFilename = img.getOriginalFilename();log.debug("头像名称: {}", originalFilename);log.debug("头像大小: {}", img.getSize());log.debug("上传的路径: {}",realpath);//1.处理头像的上传&& 修改文件名String fileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmsssSSS").format(new Date());String fileNameSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));String newFileName=fileNamePrefix+fileNameSuffix;img.transferTo(new File(realpath,newFileName));//2.保存员工信息employee.setPhoto(newFileName);employeeService.save(employee);return "redirect:/employee/lists";}

Service

 public void save(Employee employee) {employeeMapper.save(employee);}

Mapper

    <insert id="save" parameterType="Employee" useGeneratedKeys="true" keyProperty="id">insert into `employee` values (#{id},#{name},#{salary},#{birthday},#{photo})</insert>

5.更新员工的实现

在这里插入图片描述

Controller

 /*** 更新员工信息* @param employee* @param img* @return*/@RequestMapping("update")public String update(Employee employee,MultipartFile img) throws IOException {log.debug("更新之后员工信息: id:{},姓名:{},工资:{},生日:{},", employee.getId(), employee.getName(), 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";//更新成功后,跳转到所有员工列表}//上传头像方法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;}

Service

  public void update(Employee employee) {employeeMapper.update(employee);}

Mapper

 <update id="update" parameterType="Employee" >update `employee` set name=#{name},salary=#{salary},birthday=#{birthday},photo=#{photo}where id = #{id}</update>

6.删除员工的实现

Controller

    @RequestMapping("delete")public String delete(Integer id){log.debug("删除的员工id: {}",id);//1.删除数据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";//跳转到员工列表}

Service

public void delete(Integer id) {employeeMapper.delete(id);}

Mapper

  <!--delete--><delete id="delete" parameterType="Integer">delete from `employee` where id = #{id}</delete>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/674482.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【自然语言处理-工具篇】spaCy<2>--模型的使用

前言 之前已经介绍了spaCy的安装,接下来我们要通过下载和加载模型去开始使用spaCy。 下载模型 经过训练的 spaCy 管道可以作为 Python 包安装。这意味着它们是应用程序的一个组件,就像任何其他模块一样。可以使用 spaCy download的命令安装模型,也可以通过将 pip 指向路径或…

004集—二调数据库标注分子分母模式及统计净面积——arcgis

二调数据库中分子分母标注方法为&#xff1a; 表达式如下&#xff1a; "<und>"& [TBBH] &"</und>" &vbnewline& [DLBM] "<und>"&[DLBM]&"</und>" &vbnewline& [DLMC] &quo…

一文读懂:MybatisPlus从入门到进阶

快速入门 简介 在项目开发中&#xff0c;Mybatis已经为我们简化了代码编写。 但是我们仍需要编写很多单表CURD语句&#xff0c;MybatisPlus可以进一步简化Mybatis。 MybatisPlus官方文档&#xff1a;https://www.baomidou.com/&#xff0c;感谢苞米豆和黑马程序员。 Mybat…

zk集群--集群同步

1.概述 前面一章分析了集群下启动阶段选举过程&#xff0c;一旦完成选举&#xff0c;通过执行QuorumPeer的setPeerState将设置好选举结束后自身的状态。然后&#xff0c;将再次执行QuorumPeer的run的新的一轮循环&#xff0c; QuorumPeer的run的每一轮循环&#xff0c;先判断…

Python面试题13-18

解释Python中的字典推导式&#xff08;dictionary comprehensions&#xff09;是什么&#xff0c;以及它们的作用&#xff1f; 字典推导式是一种用来创建字典的简洁方式&#xff0c;类似于列表推导式。它允许在一行代码中根据某种规则从可迭代对象中创建字典。解释Python中的虚…

【学网攻】 第(23)节 -- PPP协议

系列文章目录 目录 系列文章目录 文章目录 前言 一、PPP协议是什么&#xff1f; 二、实验 1.引入 实验目的 实验背景你是某公司的网络管理员&#xff0c;现在需要与另一个公司进行通信,需要你配置PPP协议保证双方发送的人是真正的而非黑客 技术原理 实验步骤新建Pack…

【NLP冲吖~】二、隐马尔可夫模型(Hidden Markov model, HMM)

0、马尔可夫模型 某一状态只由前一个状态决定&#xff0c;即为一阶马尔可夫模型&#xff1b; 状态间的转移依赖于前n个状态的过程&#xff0c;即为n阶马尔可夫模型 马尔科夫链&#xff1a; 如果 S t 1 S_{t1} St1​只依赖于前一时刻 S t S_t St​&#xff0c;不依赖于 S 1 , …

Midjourney提示词风格调试测评

在Midjourney中提示词及风格参数的变化无疑会对最终的作品产生影响&#xff0c;那影响具体有多大&#xff1f;今天我我们将通过一个示例进行探究。 示例提示词&#xff1a; 计算机代码海洋中的黄色折纸船&#xff08;图像下方&#xff09;风格参考:金色长发的女人&#xff0c…

单片机——ISP下载、ICP下载、IAP下载

文章目录 ISPICPIAP ISP 在线系统编程&#xff0c;使用引导程序加上外围UART/SPI接口烧录 其本质是将程序的hex文件烧录到板子里的过程 可以使用flymcu这个软件 System memory是STM32在出厂时&#xff0c;由ST在这个区域内部预置了一段BootLoader&#xff0c; 也就是我们常说…

Hair Tool for Blender3D

CGer.com - Hair Tool for Blender3D - CGer资源网 Hair Tool 1.5 for Blender3D 链接: https://pan.baidu.com/s/1kVABn6n 密码: gwprHair Tool 1.65-1.8 for Blender链接: https://pan.baidu.com/s/1A7cW_Ms2baGQ2M0iE1dQhQ 密码: 81bqHair Tool for Blender 1.9.2链接: http…

SpringCache缓存快速实现注解

SpringCache是一个框架&#xff0c;只需要添加一个注解&#xff0c;就能实现缓存功能的实现&#xff0c;常用的就是Redis的缓存实现 依赖 spring-boot-starter-data-redis 与 spring-boot-starter-cache EnableCatching标注在启动类上&#xff0c;开启基于注解的缓存功能 …

【C++】C++的简要介绍

简单不先于复杂&#xff0c;而是在复杂之后。 文章目录 1. 什么是C2. C的发展史3. C的重要性3.1 语言的使用广泛度3.2 在工作领域3.3 在校招领域3.3.1 岗位需求3.3.2 笔试题 3.3.3 面试题 4. 如何学习C4.1 别人怎么学&#xff1f; 1. 什么是C C语言是结构化和模块化的语言&…

深度分析一款新型Linux勒索病毒

前言 DarkRadiation勒索病毒是一款全新的Linux平台下的勒索病毒&#xff0c;2021年5月29日首次在某平台上发布了此勒索病毒的相关的信息&#xff0c;6月中旬趋势科技针对这个新型的勒索病毒进行了相关的分析和报道。 DarkRadiation勒索病毒采用Bash脚本语言编写实现&#xff0…

Acwing---143. 最大异或对

最大异或对 1.题目2.基本思想3.代码实现 1.题目 在给定的 N个整数 A1&#xff0c;A2……AN 中选出两个进行 xor&#xff08;异或&#xff09;运算&#xff0c;得到的结果最大是多少&#xff1f; 输入格式 第一行输入一个整数 N。 第二行输入 N 个整数 A1&#xff5e;AN。 输…

最好的 4 个 Android 屏幕解锁锁软件免费下载

实际上&#xff0c;如今每个 Android 智能手机用户都将手机设置为图案锁定。此功能可以保护隐私&#xff0c;特别是当用户不在打电话时。通过绘制锁定屏幕图案&#xff0c;用户可以解锁手机&#xff0c;然后访问其主屏幕。如果用户被锁定在电话模式之外会发生什么&#xff1f;“…

基于SpringBoot3的快速迭代平台

SpringBoot3的快速开发平台 前言一、技术栈二、项目结构三、总结 前言 MateBoot是一个基于SpringBoot3的快速开发平台&#xff0c;采用前后端分离的模式&#xff0c;前端采用Element Plus组件&#xff0c;后端采用SpringBoot3、Sa-token、Mybatis-Plus、Redis、RabbitMQ、Fast…

华为第二批难题一:基于预训练AI模型的元件库生成

我的理解&#xff1a;华为的这个难道应该是想通过大模型技术&#xff0c;识别元件手册上的图文内容&#xff0c;与现有建库工具结合&#xff0c;有潜力按标准生成各种库模型。 正好&#xff0c;我们正在研究&#xff0c;利用知识图谱技术快速生成装配模型&#xff0c;其中也涉…

图像处理入门:OpenCV的基础用法解析

图像处理入门&#xff1a;OpenCV的基础用法解析 引言OpenCV的初步了解深入理解OpenCV&#xff1a;计算机视觉的开源解决方案什么是OpenCV&#xff1f;OpenCV的主要功能1. 图像处理2. 图像分析3. 结构分析和形状描述4. 动态分析5. 三维重建6. 机器学习7. 目标检测 OpenCV的应用场…

力扣热题100_哈希_49_字母异位词分组

文章目录 题目链接解题思路解题代码 题目链接 49. 字母异位词分组 给你一个字符串数组&#xff0c;请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。 字母异位词 是由重新排列源单词的所有字母得到的一个新单词。 示例 1: 输入: strs [“eat”, “tea”, “ta…

LeetCode魔塔游戏

题目描述 小扣当前位于魔塔游戏第一层&#xff0c;共有 N 个房间&#xff0c;编号为 0 ~ N-1。每个房间的补血道具/怪物对于血量影响记于数组 nums&#xff0c;其中正数表示道具补血数值&#xff0c;即血量增加对应数值&#xff1b;负数表示怪物造成伤害值&#xff0c;即血量减…