SpringBoot+Mybatis-Plus+Thymeleaf 实现增删改查+登录/注册
创始人
2024-02-17 11:23:30
0

SQL

-- `student_info`
create table if not exists `student_info`
(
`sid` int not null auto_increment comment '学生表主键' primary key,
`sname` varchar(20) not null comment '学生账号登录名、姓名',
`pwd` varchar(32) not null comment '密码',
`sex` varchar(20) not null comment '性别、男或女',
`mobile` varchar(11) not null comment '手机号',
`email` varchar(50) not null comment '邮箱'
) comment '`student_info`';
insert into `student_info` (`sid`, `sname`, `pwd`, `sex`, `mobile`, `email`) values (1, '林子骞', '882038', '男', '15935418717', 'dora.fadel@hotmail.com');
insert into `student_info` (`sid`, `sname`, `pwd`, `sex`, `mobile`, `email`) values (2, '王展鹏', '938486', '女', '15893542626', 'sherwood.goyette@gmail.com');
insert into `student_info` (`sid`, `sname`, `pwd`, `sex`, `mobile`, `email`) values (3, '孙明哲', '227987', '男', '17615636437', 'kanisha.pouros@hotmail.com');
insert into `student_info` (`sid`, `sname`, `pwd`, `sex`, `mobile`, `email`) values (4, '许思', '620600', '女', '15004232582', 'andreas.shanahan@gmail.com');
insert into `student_info` (`sid`, `sname`, `pwd`, `sex`, `mobile`, `email`) values (5, '孟明辉', '371096', '男', '17353566984', 'myra.kozey@hotmail.com');-- `score_info`
create table if not exists `score_info`
(
`scid` int not null auto_increment comment '课程表主键' primary key,
`scname` varchar(20) not null comment '课程名称',
`score` float(5, 2) not null comment '课程分数',
`sid` int not null comment '学生ID'
) comment '`score_info`';
insert into `score_info` (`scid`, `scname`, `score`, `sid`) values (1, '软件工程', 100.00, 1);
insert into `score_info` (`scid`, `scname`, `score`, `sid`) values (2, '大数据科学与技术', 100.00, 1);
insert into `score_info` (`scid`, `scname`, `score`, `sid`) values (3, '计算机科学与技术', 100.00, 1);
insert into `score_info` (`scid`, `scname`, `score`, `sid`) values (4, '软件工程', 100.00, 2);
insert into `score_info` (`scid`, `scname`, `score`, `sid`) values (5, '大数据科学与技术', 100.00, 2);
insert into `score_info` (`scid`, `scname`, `score`, `sid`) values (6, '计算机科学与技术', 100.00, 2);
insert into `score_info` (`scid`, `scname`, `score`, `sid`) values (7, '软件工程', 100.00, 3);
insert into `score_info` (`scid`, `scname`, `score`, `sid`) values (8, '大数据科学与技术', 100.00, 3);
insert into `score_info` (`scid`, `scname`, `score`, `sid`) values (9, '计算机科学与技术', 100.00, 3);
insert into `score_info` (`scid`, `scname`, `score`, `sid`) values (10, '软件工程', 100.00, 4);
insert into `score_info` (`scid`, `scname`, `score`, `sid`) values (11, '大数据科学与技术', 100.00, 4);
insert into `score_info` (`scid`, `scname`, `score`, `sid`) values (12, '计算机科学与技术', 100.00, 4);
insert into `score_info` (`scid`, `scname`, `score`, `sid`) values (13, '软件工程', 100.00, 5);
insert into `score_info` (`scid`, `scname`, `score`, `sid`) values (14, '大数据科学与技术', 100.00, 5);
insert into `score_info` (`scid`, `scname`, `score`, `sid`) values (15, '计算机科学与技术', 100.00, 5);

推荐一个网站:代码生成 - SQL之父 (sqlfather.com) 

能快速生成SQL语句并添加数据

pom.xml


4.0.0org.springframework.bootspring-boot-starter-parent2.7.5 com.exampleMybatis-Plus0.0.1-SNAPSHOTMybatis-PlusMybatis-Plus1.8org.springframework.bootspring-boot-starter-thymeleaforg.springframework.bootspring-boot-starter-webcom.mysqlmysql-connector-jruntimeorg.projectlomboklomboktrueorg.springframework.bootspring-boot-starter-testtestcom.baomidoumybatis-plus-boot-starter3.5.2com.baomidoumybatis-plus-generator3.5.3org.apache.velocityvelocity1.7org.springframework.bootspring-boot-maven-pluginorg.projectlomboklombok

application.yml

server:port: 8080spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/student?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=trueusername: rootpassword: 123456thymeleaf:cache: falsemybatis-plus:configuration:map-underscore-to-camel-case: true # 开启驼峰法则auto-mapping-behavior: fulllog-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 开启SQL打印mapper-locations: classpath*:mapper/**/*Mapper.xml # 存放sql语句的xml文件目录

CodeGeneratorUtils.java

官方文档

代码生成器(新) | MyBatis-Plus (baomidou.com)

/*** 

* MyBatisPlus代码生成器*

*/ public class CodeGeneratorUtils {/*** 执行 run TODO 注意修改TODO处的信息*/public static void main(String[] args) {// TODO 数据库配置(DataSourceConfig)String url = "jdbc:mysql://localhost:3306/student?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true";FastAutoGenerator.create(url, "root", "123456")// 全局配置(GlobalConfig).globalConfig(builder -> {builder.disableOpenDir() // 禁止打开输出目录.outputDir(System.getProperty("user.dir") + "/src/main/java") // 指定输出目录.author("YSX") // TODO 作者名.commentDate("yyyy-MM-dd hh:mm:ss"); // 注释日期})// 包配置(PackageConfig).packageConfig(builder -> {builder.parent("com.example") // TODO 设置父包名.moduleName("mybatisplus") // TODO 设置父包模块名(即启动类所在包的包名).entity("pojo") // 设置 Entity 包名.service("service") // 设置 Service 包名.serviceImpl("service.impl") // 设置 Service Impl 包名.mapper("mapper") // 设置 Mapper 包名.xml("mapper") // 设置 Mapper XML 包名.controller("controller") // 设置 Controller 包名.pathInfo(Collections.singletonMap(OutputFile.xml, System.getProperty("user.dir") + "/src/main/resources/mapper")); // 设置mapperXml生成路径})// 策略配置(StrategyConfig).strategyConfig(builder -> {builder.addInclude("score_info,student_info") // 设置需要生成的表名,多个表名用英文逗号隔开// Entity 策略配置.entityBuilder().enableTableFieldAnnotation() // 开启生成实体时生成字段注解.naming(NamingStrategy.underline_to_camel) // 数据库表映射到实体的命名策略 默认下划线转驼峰命名:NamingStrategy.underline_to_camel.idType(IdType.AUTO) // 全局主键类型.enableFileOverride() // 覆盖已生成文件// Controller 策略配置.controllerBuilder().enableFileOverride() // 覆盖已生成文件// Mapper 策略配置.mapperBuilder().superClass(BaseMapper.class) // 设置父类.enableFileOverride() // 覆盖已生成文件// Service 策略配置.serviceBuilder().superServiceClass(IService.class).superServiceImplClass(ServiceImpl.class).enableFileOverride(); // 覆盖已生成文件}).execute();} }

注意

在全局配置中的用于覆盖已生成文件的方法fileOverride方法3.5.3版本中已被弃用,然而官方文档中目前还未更新。

点进源码可以看见:

继续查看源码可知:

与之前版本不同的是,现在配置Entity、Mapper、Service、Controller覆盖已生成文件需要单独配置,而不是像之前一样在全局配置中配置一次,所有已生成的文件都会被覆盖。

在包配置中用于给生成的文件设置生成路径的pathInfo方法中设置xml文件生成路径时使用OutputFile.mapperXml会报错应改为OutputFile.xml,然而官方文档中目前还未更新。

Mapper策略配置中用于给mapper接口添加@Mapper注解的enableMapperAnnotation方法3.5.3版本中已被弃用,然而官方文档中目前还未更新。

不写该方法也可以,因为在启动类上加了@MapperScan注解

@MapperScan("com.example.mybatisplus.mapper")

对比

MyBatis-Plus CRUD接口文档

CRUD 接口 | MyBatis-Plus (baomidou.com)

登录

LoginController.java

@Controller
@RequestMapping("/mybatisplus/login")
public class LoginController {final IStudentInfoService studentInfoService;public LoginController(IStudentInfoService StudentInfoService) {this.studentInfoService = StudentInfoService;}//    @Autowired
//    private IStudentInfoService StudentInfoService;/*** 跳转到登录页面** @return 登录页面*/@RequestMapping("/studentlogin")public String studentlogin() {return "login";}/*** 登录学生的id*/static int sid;/*** 登录操作** @param sname 用户名* @param pwd   密码* @return 学生个人成绩页面*/@RequestMapping("/studentscores")public String Login(@RequestParam String sname, @RequestParam String pwd) {StudentInfo studentInfo = studentInfoService.getOne(new QueryWrapper().eq("sname", sname).eq("pwd", pwd));sid = studentInfo.getSid();return "redirect:/mybatisplus/scoreInfo/scores";}
}

使用字段注入或者构造函数注入都可以,Spring官方推荐使用构造函数注入。

login.html


学生登录

学生登录

注意


上面两行代码一定要按顺序排列,不能反过来。之后的页面代码也是这样,不能反过来。

common.css一定要在上面

common.css

* {margin: 0;padding: 0;
}.content {position: absolute;top: 0;left: 0;right: 0;bottom: 0;margin: auto;text-align: center;border-radius: 20px;border: 1px solid black;
}form {margin: 20px;
}input:not([type="submit"]) {width: 180px;height: 30px;border-radius: 10px;border: 1px solid black;
}input[type="submit"], button {width: 100px;height: 40px;margin-top: 15px;border-radius: 10px;border: 1px solid black;
}a {color: black;text-decoration: none;
}

login.css

.content {width: 350px;height: 240px;
}input:not([type="submit"]) {margin-bottom: 20px;
}

页面效果

注册

RegisterController.java

@Controller
@RequestMapping("/mybatisplus/register")
public class RegisterController {final IStudentInfoService studentInfoService;public RegisterController(IStudentInfoService StudentInfoService) {this.studentInfoService = StudentInfoService;}/*** 学生注册** @return 学生注册页面*/@RequestMapping("/studentregister")public String studentregister() {return "register";}/*** 学生信息注册操作** @param studentInfo 学生信息* @return 登录页面*/@RequestMapping("/studentInforegister")private String studentInforegister(StudentInfo studentInfo) {studentInfoService.save(studentInfo);return "login";}
}

register.html


学生注册

学生注册

register.css

.content {width: 400px;height: 370px;
}input:not([type="submit"]) {margin-top: 15px;
}

页面效果

学生成绩增删改查

ScoreInfoController.java

import org.springframework.ui.Model;@Controller
@RequestMapping("/mybatisplus/scoreInfo")
public class ScoreInfoController {final IScoreInfoService scoreInfoService;public ScoreInfoController(IScoreInfoService scoreInfoService) {this.scoreInfoService = scoreInfoService;}/*** 跳转到指定学生的成绩页面** @param model 指定学生的成绩列表* @return 指定学生的成绩页面*/@RequestMapping("/scores")private String scores(Model model) {List scoreInfoList = scoreInfoService.list(new QueryWrapper().eq("sid",  LoginController.sid));model.addAttribute("scoreInfoList", scoreInfoList);return "scoreList";}/*** 跳转到指定学生的成绩添加页面** @param model 指定学生的id* @return 指定学生的成绩添加页面*/@RequestMapping("/scoreInfoAdd")private String scoreInfoAdd(Model model) {model.addAttribute("sid",  LoginController.sid);return "scoreAdd";}/*** 指定学生的成绩添加操作** @param scoreInfo 指定学生的成绩信息* @return 学生的成绩页面*/@RequestMapping("/AddScoreInfo")private String addScoreInfo(ScoreInfo scoreInfo) {scoreInfoService.save(scoreInfo);return "redirect:/mybatisplus/scoreInfo/scores";}/*** 删除学生指定成绩** @param scid 成绩主键id* @return 学生的成绩页面*/@RequestMapping("/RemoveScoreInfo/{scid}")private String removeScoreInfoById(@PathVariable Integer scid) {scoreInfoService.removeById(scid);return "redirect:/mybatisplus/scoreInfo/scores";}/*** 跳转到更新学生指定成绩页面** @param scid  成绩id* @param model 学生指定成绩信息* @return 成绩更新页面*/@RequestMapping("/scoreInfoUpdate/{scid}")private String scoreInfoUpdate(@PathVariable("scid") Integer scid, Model model) {ScoreInfo scoreInfo = scoreInfoService.getById(scid);model.addAttribute("scoreInfo", scoreInfo);return "scoreUpdate";}/*** 更新学生指定成绩操作** @param scoreInfo 指定学生的成绩信息* @return 学生的成绩页面*/@RequestMapping("/UpdateScoreInfo")private String updateScoreInfoById(ScoreInfo scoreInfo) {scoreInfoService.updateById(scoreInfo);return "redirect:/mybatisplus/scoreInfo/scores";}/*** 通过课程名称查询学生成绩** @param model  学生成绩信息* @param scname 课程名称* @return 学生信息页面*/@RequestMapping("/QueryScoreInfo")public String queryScoreInfo(Model model, @RequestParam String scname) {List scoreInfoList = scoreInfoService.list(new QueryWrapper().eq("scname", scname).eq("sid",  LoginController.sid));model.addAttribute("scoreInfoList", scoreInfoList);return "scoreList";}
}

scoreList.html


学生个人成绩

学生个人成绩

编号课程成绩操作
修改删除

scoreList.css

.content {border: 0;
}input:not([type="submit"]) {margin-bottom: 20px;
}input[type="submit"], button {width: 90px;
}table {width: 900px;margin: auto;
}

页面效果

scoreAdd.html


添加学生成绩

添加学生成绩

scoreAdd.css

.content {width: 400px;height: 270px;
}input:not([type="submit"]) {margin-top: 15px;
}

页面效果

scoreUpdate.html


修改学生成绩

修改学生成绩

scoreUpdate.css

.content {width: 400px;height: 270px;
}input:not([type="submit"]) {margin-top: 15px;
}

页面效果

补充

下面代码是学生信息的增删改查后端代码,前端代码可以参照上面的代码编写。注意路径

import org.springframework.ui.Model;@Controller
@RequestMapping("/mybatisplus/studentInfo")
public class StudentInfoController {final IStudentInfoService studentInfoService;public StudentInfoController(IStudentInfoService studentInfoService) {this.studentInfoService = studentInfoService;}// TODO 下面代码须要添加路径(1/2/3/4/5/6/7)/*** 跳转到学生信息页面** @param model 学生信息列表* @return 学生信息页面*/@RequestMapping("/1")public String studentInfoList(Model model) {List studentInfos = studentInfoService.list();model.addAttribute("studentInfos", studentInfos);return "";}/*** 跳转到学生信息添加页面** @return 学生信息添加页面*/@RequestMapping("/2")private String studentInfoAdd() {return "";}/*** 学生信息添加操作** @param studentInfo 学生信息* @return 学生信息页面*/@RequestMapping("/3")private String addStudentInfo(StudentInfo studentInfo) {studentInfoService.save(studentInfo);return "";}/*** 删除指定学生信息操作** @param id 学生id* @return 学生信息页面*/@RequestMapping("/4/{id}")private String removeStudentInfo(@PathVariable Integer id) {studentInfoService.removeById(id);return "";}/*** 跳转到更新学生信息页面** @param id    学生id* @param model 学生信息* @return 学生信息更新页面*/@RequestMapping("/5/{id}")private String studentInfoUpdate(@PathVariable("id") Integer id, Model model) {StudentInfo studentInfo = studentInfoService.getById(id);model.addAttribute("studentInfo", studentInfo);return "";}/*** 更新学生信息操作** @param studentInfo 学生信息* @return 学生信息页面*/@RequestMapping("/6")private String updateStudentInfo(StudentInfo studentInfo) {studentInfoService.updateById(studentInfo);return "";}/*** 通过姓名查询学生信息** @param model 学生信息* @param sname 学生姓名* @return 学生信息页面*/@RequestMapping("/7")public String queryStudentInfo(Model model, @RequestParam String sname) {List studentInfoList = studentInfoService.list(new QueryWrapper().eq("sname", sname));model.addAttribute("studentInfoList", studentInfoList);return "";}
}

相关内容

热门资讯

喜欢穿一身黑的男生性格(喜欢穿... 今天百科达人给各位分享喜欢穿一身黑的男生性格的知识,其中也会对喜欢穿一身黑衣服的男人人好相处吗进行解...
网络用语zl是什么意思(zl是... 今天给各位分享网络用语zl是什么意思的知识,其中也会对zl是啥意思是什么网络用语进行解释,如果能碰巧...
发春是什么意思(思春和发春是什... 本篇文章极速百科给大家谈谈发春是什么意思,以及思春和发春是什么意思对应的知识点,希望对各位有所帮助,...
为什么酷狗音乐自己唱的歌不能下... 本篇文章极速百科小编给大家谈谈为什么酷狗音乐自己唱的歌不能下载到本地?,以及为什么酷狗下载的歌曲不是...
苏州离哪个飞机场近(苏州离哪个... 本篇文章极速百科小编给大家谈谈苏州离哪个飞机场近,以及苏州离哪个飞机场近点对应的知识点,希望对各位有...
家里可以做假山养金鱼吗(假山能... 今天百科达人给各位分享家里可以做假山养金鱼吗的知识,其中也会对假山能放鱼缸里吗进行解释,如果能碰巧解...
华为下载未安装的文件去哪找(华... 今天百科达人给各位分享华为下载未安装的文件去哪找的知识,其中也会对华为下载未安装的文件去哪找到进行解...
四分五裂是什么生肖什么动物(四... 本篇文章极速百科小编给大家谈谈四分五裂是什么生肖什么动物,以及四分五裂打一生肖是什么对应的知识点,希...
怎么往应用助手里添加应用(应用... 今天百科达人给各位分享怎么往应用助手里添加应用的知识,其中也会对应用助手怎么添加微信进行解释,如果能...
客厅放八骏马摆件可以吗(家里摆... 今天给各位分享客厅放八骏马摆件可以吗的知识,其中也会对家里摆八骏马摆件好吗进行解释,如果能碰巧解决你...