Java—基于SpringBootWeb的综合小案例(智能学习辅助系统)_javaweb案例及代码-程序员宅基地

技术标签: JAVA语言  学习  MySQL数据库  

简介:这篇帖子是小编在看哔哩哔哩网课是的一个小案例,来自于黑马程序员,我觉得他们的课讲的很好,而且这个案例很有实用性,就在看视频的基础上,边温故知新,边实现了这个代码,在一些重点、难点和在编码过程中容易出问题的地方上进行了标注、做详解。

一、准备工作

        01、需求&环境搭建

                需求说明:(如下图)

       

                环境搭建:在这篇帖子中,因为小编主攻的是后端开发工程师,所以前端工程的项目代码这边直接给出了“百度网盘:前端代码”,大家点击下载就好。(如下图)展示的是一个小项目的过程。

接下来是项目的创建过程:

        首先第一步是创建数据库表(下图第一张是源代码,第二张时操作引导)

                (指导图片:源代码图片)

-- 部门管理
create table dept(
    id int unsigned primary key auto_increment comment '主键ID',
    name varchar(10) not null unique comment '部门名称',
    create_time datetime not null comment '创建时间',
    update_time datetime not null comment '修改时间'
) comment '部门表';

insert into dept (id, name, create_time, update_time) values(1,'学工部',now(),now()),(2,'教研部',now(),now()),(3,'咨询部',now(),now()), (4,'就业部',now(),now()),(5,'人事部',now(),now());



-- 员工管理(带约束)
create table emp (
  id int unsigned primary key auto_increment comment 'ID',
  username varchar(20) not null unique comment '用户名',
  password varchar(32) default '123456' comment '密码',
  name varchar(10) not null comment '姓名',
  gender tinyint unsigned not null comment '性别, 说明: 1 男, 2 女',
  image varchar(300) comment '图像',
  job tinyint unsigned comment '职位, 说明: 1 班主任,2 讲师, 3 学工主管, 4 教研主管, 5 咨询师',
  entrydate date comment '入职时间',
  dept_id int unsigned comment '部门ID',
  create_time datetime not null comment '创建时间',
  update_time datetime not null comment '修改时间'
) comment '员工表';

INSERT INTO emp
	(id, username, password, name, gender, image, job, entrydate,dept_id, create_time, update_time) VALUES
	(1,'jinyong','123456','金庸',1,'1.jpg',4,'2000-01-01',2,now(),now()),
	(2,'zhangwuji','123456','张无忌',1,'2.jpg',2,'2015-01-01',2,now(),now()),
	(3,'yangxiao','123456','杨逍',1,'3.jpg',2,'2008-05-01',2,now(),now()),
	(4,'weiyixiao','123456','韦一笑',1,'4.jpg',2,'2007-01-01',2,now(),now()),
	(5,'changyuchun','123456','常遇春',1,'5.jpg',2,'2012-12-05',2,now(),now()),
	(6,'xiaozhao','123456','小昭',2,'6.jpg',3,'2013-09-05',1,now(),now()),
	(7,'jixiaofu','123456','纪晓芙',2,'7.jpg',1,'2005-08-01',1,now(),now()),
	(8,'zhouzhiruo','123456','周芷若',2,'8.jpg',1,'2014-11-09',1,now(),now()),
	(9,'dingminjun','123456','丁敏君',2,'9.jpg',1,'2011-03-11',1,now(),now()),
	(10,'zhaomin','123456','赵敏',2,'10.jpg',1,'2013-09-05',1,now(),now()),
	(11,'luzhangke','123456','鹿杖客',1,'11.jpg',5,'2007-02-01',3,now(),now()),
	(12,'hebiweng','123456','鹤笔翁',1,'12.jpg',5,'2008-08-18',3,now(),now()),
	(13,'fangdongbai','123456','方东白',1,'13.jpg',5,'2012-11-01',3,now(),now()),
	(14,'zhangsanfeng','123456','张三丰',1,'14.jpg',2,'2002-08-01',2,now(),now()),
	(15,'yulianzhou','123456','俞莲舟',1,'15.jpg',2,'2011-05-01',2,now(),now()),
	(16,'songyuanqiao','123456','宋远桥',1,'16.jpg',2,'2007-01-01',2,now(),now()),
	(17,'chenyouliang','123456','陈友谅',1,'17.jpg',NULL,'2015-03-21',NULL,now(),now());



                (知道图片:操作引导)

        接下来是创建SpringBoot项目,并且添加相关依赖,操作引导如下图。

                (引导图一)

                (引导图二)

                (引导图三)

                (以上图片中对应的项目代码,大家下载后直接导入就好,点击下载。但是注意要把项目中“application.properties”文件的数据库名称和密码换成自己的。)

        02、开发规范

当前主流的开发规范就是前后端分离开发,前端与后端通过阅读接口文档相互约定规则后进行开发。(如下图所示)

编码规则—ResultFul:(如下图所示)

规定一个返回规则:通过定义一个Result类,制定统一的返回结果(如下图所示)

代码详情如下:

package com.itheima.tliaswebmanagement.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
    private Integer code; //响应码: 1. 代表成功  2. 代表失败
    private String msg; //响应信息: 描述字符串
    private Object data; //返回的数据

    public static Result success(){ // 增删改 成功响应
        return new Result(1, "success", null);
    }
    public static Result success(Object data){ // 查询 成功响应
        return new Result(1, "success", data);
    }
    public static Result error(String msg){ // 失败响应
        return new Result(0, msg, null);
    }
}

二、部门管理

01、查询部门

整体思路“如下图”:首先是浏览器端发送的请求被Controller接收—>将请求发送至Service层进行逻辑处理—>处理后发送到Mapper层访问数据库—>数据库将响应的结果返回给Mapper层—>Mapper层返回给Service层—>Service层返回给Controller层—>Controller层返回给浏览器。

02、前后端联调试

前后端联调指的是将前端工程,后端工程都启动起来,通过前端工程来访问后端工程,进而进行调试。

这边小编已经将前端工程项目上传到我的网盘中,大家(点击下载),并且将其解压缩,然后运行nginx.exe可执行文件就好。

之后使用浏览器访问http://localhost:90。

03、删除部门

此功能是通过点击前端的删除部门按钮,将数据库中的对应部门数据删除掉(如下配图)。

04、新增部门

此功能是通过点击前端的新增部门按钮,将数据库中的对应部门数据增加一条(如下配图)

05、部分核心代码展示(详情代码在下面的最终代码展示)

Controller页面

package com.itheima.tliaswebmanagement.controller;

import com.itheima.tliaswebmanagement.pojo.Dept;
import com.itheima.tliaswebmanagement.pojo.Result;
import com.itheima.tliaswebmanagement.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
// 一个完整的请求路径,应该是类上的@RequestMapping的value属性+方法上的@RequestMapping的value属性。
@RequestMapping("/depts")
public class DeptController {

    @Autowired
    private DeptService deptService;

    // 获取日志对象
    //private static Logger logger = LoggerFactory.getLogger(DeptController.class);

    /*@RequestMapping(value = "/depts", method = RequestMethod.GET)*/
    /**
     * 遍历部门数据
     * @return
     */
    @GetMapping()
    public Result list(){
        /*logger.info("通过日志工厂,获取的日志对象: " + );*/

        log.info("查询全部部门数据");

        List<Dept> deptList = deptService.list();

        return Result.success(deptList);
    }

    /**
     * 根据id删除部门
     * @return
     */
    @DeleteMapping("/{id}")
    public Result deleteByID(@PathVariable Integer id){
        log.info("根据部门ID删除部门:{}", id);
        deptService.deleteByID(id);
        return Result.success();
    }

    /**
     * 向部门插入数据
     * @return Result
     */
    @PostMapping()
    public Result insert(@RequestBody Dept dept){
        log.info("新增部门: {}", dept);
        deptService.insert(dept);
        return Result.success();
    }
}

Service层

package com.itheima.tliaswebmanagement.service.impl;

import com.itheima.tliaswebmanagement.mapper.DeptMapper;
import com.itheima.tliaswebmanagement.pojo.Dept;
import com.itheima.tliaswebmanagement.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    @Override
    public void deleteByID(Integer id) {
        deptMapper.deleteByID(id);
    }

    @Override
    public void insert(Dept dept) {
        //补全Dept表中的时间属性
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insert(dept);
    }

}

Dao层

package com.itheima.tliaswebmanagement.mapper;

import com.itheima.tliaswebmanagement.pojo.Dept;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 部门管理
 */

@Mapper
public interface DeptMapper {

    /**
     * 查询全部部门数据
     * @return
     */
    @Select("select * from dept")
    List<Dept> list();

    /**
     * 通过部门ID删除部门
     * @param id
     */
    @Delete("delete from dept where id = #{id}")
    void deleteByID(Integer id);

    /**
     * 向部门表插入一个数据
     * @param id
     */
    @Insert("insert into dept(name, create_time, update_time ) values(#{name}, #{createTime}, #{updateTime})")
    void insert(Dept dept);
}

三、员工管理

01、分页查询

此功能是通过点击前端的查询员工按钮,将数据库中的对应员工数据按照约定的格式返回给前端(如下配图)

在项目前端中就能看到我们从数据库中查到的员工数据如下。

小结如下:

02、条件分页查询

这里主要的的难点在于将SQL查询语句统一书写到XMl文件中。如下图所示,在这里使用了动态SQL语句,用以实现条件查询。

<?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.itheima.tliaswebmanagement.mapper.EmpMapper">
    
    <select id="list" resultType="com.itheima.tliaswebmanagement.pojo.Emp">

    select * from emp
    <where>
        <if test="name != null and name != '' ">
            name like concat('%', #{name}, '%')
        </if>
        <if test="gender != null">
           and gender = #{gender}
        </if>
        <if test="begin != null and end != null">
            and entrydate between #{begin} and #{end}
        </if>
    </where>
    order by update_time desc
    </select>
</mapper>

03、删除员工

这里主要是通过动态SQL实现批量删除员工表中的员工信息,这里只展示一些核心代码,最终完整项目在文章底部提供链接。

Controller层

package com.itheima.tliaswebmanagement.controller;

import com.itheima.tliaswebmanagement.pojo.PageBean;
import com.itheima.tliaswebmanagement.pojo.Result;
import com.itheima.tliaswebmanagement.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

/**
 * 员工管理类
 */

@Slf4j
@RestController
@RequestMapping("/emps")
public class EmpController {

    @Autowired
    private EmpService empService;

    /**
     * 员工管理-分页查询
     * @param page 页码
     * @param pageSize 每页多少数据
     */
    @GetMapping()
    public Result page(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize,
                       String name, Short gender,
                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end){
        PageBean pageBean = empService.page(page, pageSize, name, gender, begin, end);
        log.info("分页查询参数: {},{},{}, {}, {}", page, pageSize, name, gender, begin, end);
        return Result.success(pageBean);
    }

    /**
     * 员工管理-删除员工数据
     * @param
     * @return
     */
    @DeleteMapping("/{ids}")
    public Result deleteById(@PathVariable List<Integer> ids){

        log.info("要删除员工数据id: {}", ids);
        empService.deleteById(ids);
        return Result.success();
    }
}

Service层

package com.itheima.tliaswebmanagement.service;

import com.itheima.tliaswebmanagement.pojo.PageBean;
import org.springframework.format.annotation.DateTimeFormat;

import java.time.LocalDate;
import java.util.List;

/**
 * 员工管理
 */
public interface EmpService {

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    PageBean page(Integer page, Integer pageSize, String name, Short gender, LocalDate begin, LocalDate end);

    /**
     * 根据id删除用户
     */
    void deleteById(List<Integer> ids);
}

Dao层

package com.itheima.tliaswebmanagement.mapper;

import com.itheima.tliaswebmanagement.pojo.Emp;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDate;
import java.util.List;

/**
 * 员工管理
 */

@Mapper
public interface EmpMapper {

    // 以下代码是使用PageHelper插件进行增删查改的代码。
    /**
     * 查询员工表所有数据
     * @return
     */
/*    @Select("select * from emp")*/
    public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);

    /**
     * 根据id删除用户
     */
    void deleteById(List<Integer> ids);


    // 以下代码是不使用PageHelper插件进行增删查改的代码。
    /*    *//**
     * 查询消息记录数
     * @return
     *//*
    @Select("select count(*) from  emp")
    public Long count();

    *//**
     * 分页查询,获取列表数据
     * @return
     *//*
    @Select("select * from emp limit #{page}, #{pageSize}")
    List<Emp> page(Integer page, Integer pageSize);*/
}

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.itheima.tliaswebmanagement.mapper.EmpMapper">

    <select id="list" resultType="com.itheima.tliaswebmanagement.pojo.Emp">

        select * from emp
        <where>
            <if test="name != null and name != '' ">
                name like concat('%', #{name}, '%')
            </if>
            <if test="gender != null">
                and gender = #{gender}
            </if>
            <if test="begin != null and end != null">
                and entrydate between #{begin} and #{end}
            </if>
        </where>
        order by update_time desc
    </select>

    <delete id="deleteById">
        delete from emp
        <where>
            id in
            <foreach collection="ids" item="id" separator="," open="(" close=")">
                #{id}
            </foreach>
        </where>
    </delete>
</mapper>

        总结:因为只是一个小项目,而且后面的功能要么就是简单的重复操作,要么就是更深层次的技术点,例如账号管理(注册、登录等),这个小编打算作为单独的一个文章讲解,所以目前为止只提供这么多讲解,如果继续文章就太杂乱了。

        这边也建议如果打算想更深层次的学习,可以去哔哩哔哩里面系统的观看他们的网课,然后有不懂得问题或者BUG可以随时给我留言,会非常热心的给出解答,甚至如果出现多人问同一问题,我这边也能在写一篇帖子做解答。

        小编的QQ:2917281717

        希望大家给个点赞、留言、关注,你的认可就是我坚持下去的动力。

        项目的百度链接如下(点击下载)。

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Wang_ning__/article/details/134742321

智能推荐

oracle 12c 集群安装后的检查_12c查看crs状态-程序员宅基地

文章浏览阅读1.6k次。安装配置gi、安装数据库软件、dbca建库见下:http://blog.csdn.net/kadwf123/article/details/784299611、检查集群节点及状态:[root@rac2 ~]# olsnodes -srac1 Activerac2 Activerac3 Activerac4 Active[root@rac2 ~]_12c查看crs状态

解决jupyter notebook无法找到虚拟环境的问题_jupyter没有pytorch环境-程序员宅基地

文章浏览阅读1.3w次,点赞45次,收藏99次。我个人用的是anaconda3的一个python集成环境,自带jupyter notebook,但在我打开jupyter notebook界面后,却找不到对应的虚拟环境,原来是jupyter notebook只是通用于下载anaconda时自带的环境,其他环境要想使用必须手动下载一些库:1.首先进入到自己创建的虚拟环境(pytorch是虚拟环境的名字)activate pytorch2.在该环境下下载这个库conda install ipykernelconda install nb__jupyter没有pytorch环境

国内安装scoop的保姆教程_scoop-cn-程序员宅基地

文章浏览阅读5.2k次,点赞19次,收藏28次。选择scoop纯属意外,也是无奈,因为电脑用户被锁了管理员权限,所有exe安装程序都无法安装,只可以用绿色软件,最后被我发现scoop,省去了到处下载XXX绿色版的烦恼,当然scoop里需要管理员权限的软件也跟我无缘了(譬如everything)。推荐添加dorado这个bucket镜像,里面很多中文软件,但是部分国外的软件下载地址在github,可能无法下载。以上两个是官方bucket的国内镜像,所有软件建议优先从这里下载。上面可以看到很多bucket以及软件数。如果官网登陆不了可以试一下以下方式。_scoop-cn

Element ui colorpicker在Vue中的使用_vue el-color-picker-程序员宅基地

文章浏览阅读4.5k次,点赞2次,收藏3次。首先要有一个color-picker组件 <el-color-picker v-model="headcolor"></el-color-picker>在data里面data() { return {headcolor: ’ #278add ’ //这里可以选择一个默认的颜色} }然后在你想要改变颜色的地方用v-bind绑定就好了,例如:这里的:sty..._vue el-color-picker

迅为iTOP-4412精英版之烧写内核移植后的镜像_exynos 4412 刷机-程序员宅基地

文章浏览阅读640次。基于芯片日益增长的问题,所以内核开发者们引入了新的方法,就是在内核中只保留函数,而数据则不包含,由用户(应用程序员)自己把数据按照规定的格式编写,并放在约定的地方,为了不占用过多的内存,还要求数据以根精简的方式编写。boot启动时,传参给内核,告诉内核设备树文件和kernel的位置,内核启动时根据地址去找到设备树文件,再利用专用的编译器去反编译dtb文件,将dtb还原成数据结构,以供驱动的函数去调用。firmware是三星的一个固件的设备信息,因为找不到固件,所以内核启动不成功。_exynos 4412 刷机

Linux系统配置jdk_linux配置jdk-程序员宅基地

文章浏览阅读2w次,点赞24次,收藏42次。Linux系统配置jdkLinux学习教程,Linux入门教程(超详细)_linux配置jdk

随便推点

matlab(4):特殊符号的输入_matlab微米怎么输入-程序员宅基地

文章浏览阅读3.3k次,点赞5次,收藏19次。xlabel('\delta');ylabel('AUC');具体符号的对照表参照下图:_matlab微米怎么输入

C语言程序设计-文件(打开与关闭、顺序、二进制读写)-程序员宅基地

文章浏览阅读119次。顺序读写指的是按照文件中数据的顺序进行读取或写入。对于文本文件,可以使用fgets、fputs、fscanf、fprintf等函数进行顺序读写。在C语言中,对文件的操作通常涉及文件的打开、读写以及关闭。文件的打开使用fopen函数,而关闭则使用fclose函数。在C语言中,可以使用fread和fwrite函数进行二进制读写。‍ Biaoge 于2024-03-09 23:51发布 阅读量:7 ️文章类型:【 C语言程序设计 】在C语言中,用于打开文件的函数是____,用于关闭文件的函数是____。

Touchdesigner自学笔记之三_touchdesigner怎么让一个模型跟着鼠标移动-程序员宅基地

文章浏览阅读3.4k次,点赞2次,收藏13次。跟随鼠标移动的粒子以grid(SOP)为partical(SOP)的资源模板,调整后连接【Geo组合+point spirit(MAT)】,在连接【feedback组合】适当调整。影响粒子动态的节点【metaball(SOP)+force(SOP)】添加mouse in(CHOP)鼠标位置到metaball的坐标,实现鼠标影响。..._touchdesigner怎么让一个模型跟着鼠标移动

【附源码】基于java的校园停车场管理系统的设计与实现61m0e9计算机毕设SSM_基于java技术的停车场管理系统实现与设计-程序员宅基地

文章浏览阅读178次。项目运行环境配置:Jdk1.8 + Tomcat7.0 + Mysql + HBuilderX(Webstorm也行)+ Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)。项目技术:Springboot + mybatis + Maven +mysql5.7或8.0+html+css+js等等组成,B/S模式 + Maven管理等等。环境需要1.运行环境:最好是java jdk 1.8,我们在这个平台上运行的。其他版本理论上也可以。_基于java技术的停车场管理系统实现与设计

Android系统播放器MediaPlayer源码分析_android多媒体播放源码分析 时序图-程序员宅基地

文章浏览阅读3.5k次。前言对于MediaPlayer播放器的源码分析内容相对来说比较多,会从Java-&amp;amp;gt;Jni-&amp;amp;gt;C/C++慢慢分析,后面会慢慢更新。另外,博客只作为自己学习记录的一种方式,对于其他的不过多的评论。MediaPlayerDemopublic class MainActivity extends AppCompatActivity implements SurfaceHolder.Cal..._android多媒体播放源码分析 时序图

java 数据结构与算法 ——快速排序法-程序员宅基地

文章浏览阅读2.4k次,点赞41次,收藏13次。java 数据结构与算法 ——快速排序法_快速排序法