一、添加代码生成器
用来自动为数据库映射类建立:mapper、service、controller
注:代码生成器的写法,参考官方文档:https://mp.baomidou.com/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
package com.hanmh.utils; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import com.hanmh.pojo.BasePojo; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class HanGenerator { public static void main(String[] args) { // 代码生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); //这样获取到的是父项目的目录 String projectPath = System.getProperty( "user.dir" ); String pojoProject = "pojo" + "/src/main/java/com/hanmh/pojo" ; String otherProject = "admin" ; //gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor( "hanmh" ); gc.setOpen( false ); // gc.setSwagger2(true); 实体属性 Swagger2 注解 mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl( "jdbc:mysql://39.105.231.52:3306/db?useUnicode=true&useSSL=false&characterEncoding=utf8" ); // dsc.setSchemaName("public"); dsc.setDriverName( "com.mysql.jdbc.Driver" ); dsc.setUsername( "root" ); dsc.setPassword( "123456" ); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent( "com.hanmh" ); //设置父包 //自定义生成路径 Map<String,String> pathInfo = new HashMap<String,String>(); pathInfo.put( "entity_path" , projectPath + "/" + pojoProject); //pojo位置 pathInfo.put( "controller_path" , projectPath + "/" + otherProject + "/src/main/java/com/hanmh/controller" ); pathInfo.put( "service_impl_path" , projectPath + "/" + otherProject + "/src/main/java/com/hanmh/service/impl" ); pathInfo.put( "service_path" , projectPath + "/" + otherProject + "/src/main/java/com/hanmh/service" ); pathInfo.put( "mapper_path" , projectPath + "/" + otherProject + "/src/main/java/com/hanmh/mapper" ); pathInfo.put( "xml_path" , projectPath + "/" + otherProject + "/src/main/resources/com/hanmh/mapper" ); pc.setEntity( "pojo" ); //实体类 pc.setPathInfo(pathInfo); mpg.setPackageInfo(pc); // 自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; // 如果模板引擎是 freemarker String templatePath = "/templates/mapper.xml.ftl" ; // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); //生成时,继承的父类 strategy.setSuperEntityClass(BasePojo. class ); strategy.setEntityLombokModel( true ); strategy.setRestControllerStyle( true ); // 公共父类 strategy.setSuperControllerClass( "你自己的父类控制器,没有就不用设置!" ); // 写于父类中的公共字段 strategy.setSuperEntityColumns( "id" ); strategy.setInclude( "ums_admin" ); strategy.setControllerMappingHyphenStyle( true ); strategy.setTablePrefix(pc.getModuleName() + "_" ); mpg.setStrategy(strategy); mpg.setTemplateEngine( new FreemarkerTemplateEngine()); mpg.execute(); } } |
二、导入需要的jar包
前期需要导入的包有:mybatis-plus、mysql、duracloud(工具包)、pojo、spring-boot-starter-web
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
< dependency > < groupId >com.hanmh</ groupId > < artifactId >pojo</ artifactId > </ dependency > < dependency > < groupId >org.projectlombok</ groupId > < artifactId >lombok</ artifactId > </ dependency > < dependency > < groupId >com.baomidou</ groupId > < artifactId >mybatis-plus-boot-starter</ artifactId > </ dependency > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-web</ artifactId > </ dependency > < dependency > < groupId >mysql</ groupId > < artifactId >mysql-connector-java</ artifactId > </ dependency > < dependency > < groupId >org.duracloud</ groupId > < artifactId >common</ artifactId > </ dependency > |
三、创建启动类
启动类必须创建在父包下面,注意在SpringBoot中,并不是不扫包,而是框架帮助完成了这件事,它会扫描启动类所在包下的所有类及其子包中的类
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package com.hanmh; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan ( "com.hanmh.mapper" ) public class AdminRun { public static void main(String[] args) { SpringApplication.run(AdminRun. class ); } } |
四、创建配置文件(application.yml)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
server: port: 8080 spring: application: name: admin datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://39.105.231.52:3306/db?useUnicode=true&useSSL=false&characterEncoding=utf8 username: root password: 123456 hikari: maximum-pool-size: 20 minimum-idle: 10 servlet: #文件传输配置 multipart: max-file-size: 5MB max-request-size: 10MB #运行的过程中输出sql语句(日志信息) logging: level: com.hanmh.mapper: debug |
五、返回值统一定义
1、ResultJson
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
package com.hanmh.pojo; import lombok.Data; @Data public class ResultJson { private Integer code; //200成功,500错误 private Object obj; private String message; public ResultJson(ResultCode resultCode, Object obj) { this .code = resultCode.getCode(); this .message = resultCode.getMessage(); this .obj = obj; } public ResultJson(ResultCode resultCode, Object obj, String message) { this .code = resultCode.getCode(); this .message = message; this .obj = obj; } public static ResultJson success(Object obj) { return new ResultJson(ResultCode.SUCCESS, obj); } public static ResultJson success(Object obj, String message) { return new ResultJson(ResultCode.SUCCESS, obj, message); } public static ResultJson error(Object obj) { return new ResultJson(ResultCode.ERROR, obj); } public static ResultJson error() { return new ResultJson(ResultCode.ERROR, null ); } public static ResultJson error(String message) { return new ResultJson(ResultCode.ERROR, null , message); } } |
2、ResultCode
定义4种返回代号和返回信息,使用枚举类进行实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
package com.hanmh.pojo; import lombok.Data; import lombok.Getter; @Getter public enum ResultCode { SUCCESS( 200 , "请求成功" ), ERROR( 500 , "请求失败" ), NOAUTH( 401 , "用户未登录或者登录超时" ), //操作时 NOPREMISSION( 403 , "没有此权限" ); private Integer code; private String message; //枚举类型的构造默认为私有 private ResultCode(Integer code, String message) { this .code = code; this .message = message; } } |
六、创建基础pojo
在所有的数据库表种,共有的字段是ID,现在将id独立出来
1、导入 mybatis-plus-annotation包
为了使用该包内部的IdType等类内部提供的注解,以告诉BasePojo中某些字段在数据库表中的存在与否
1
2
3
4
5
|
< dependency > < groupId >com.baomidou</ groupId > < artifactId >mybatis-plus-annotation</ artifactId > < version >3.0-RELEASE</ version > </ dependency > |
2、BasePojo类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package com.hanmh.pojo; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import org.omg.CORBA.IDLType; @Data public class BasePojo { @TableId (type = IdType.AUTO) private Integer id; //做分页操作需要的字段 @TableField (exist = false ) private Integer pageNO; @TableField (exist = false ) private Integer pageSize; } |
七、后端添加数据
1、密码加密
(1)需要使用安全包提供加密服务(security)
1
2
3
4
|
< dependency > < groupId >org.springframework.security</ groupId > < artifactId >spring-security-core</ artifactId > </ dependency > |
2、将加密类(BCryptPasswordEncoder)放入IOC容器
在SpringBoot环节,需要将某个类加入IOC容器,就需要在配置类中,配置@Bean节点
1
2
3
4
5
6
7
8
|
@Configuration public class AdminConfig { @Bean //将BCryptPasswordEncoder放进IOC容器 BCryptPasswordEncoder getPasswordEncoder() { return new BCryptPasswordEncoder(); } } |
注:使用此方法对数据进行加密的原因:此加密方法相同明文密码多次可以生成不同的密文,而MD5相同密码则会生成相同的密文
3、后端添加数据简单实现
1
2
3
4
5
6
7
8
|
@PostMapping ( "/add" ) ResultJson add(UmsAdmin umsAdmin) throws InterruptedException, IOException { //对密码加密 umsAdmin.setPassword(passwordEncoder.encode(umsAdmin.getPassword())); //TimeUnit.SECONDS.sleep(2); return ResultJson.success(adminService.save(umsAdmin), "添加用户成功" ); } |
八、前端页面添加功能
1、添加用户(按钮和弹窗)
1
2
3
4
5
6
7
8
9
10
11
|
<el-button>:elementUI按钮标签 <el-button type= "primary" plain @click= "add" >添加用户</el-button> <!-- <el-dialog> 代表弹窗 :visible.sync表示显示或隐藏--> <!-- close-on-click-modal代表点击对话框以外区域是否可以关闭 --> <el-dialog :title= "dialog.title" :visible.sync= "dialog.show" :close-on-click-modal= "false" width= "450px" > <AdminEdit :show.sync= "dialog.show" v- if = "dialog.show" ></AdminEdit> </el-dialog> |
(1)添加用户功能
1
2
3
4
|
add() { this .dialog.show = true this .dialog.title = "添加用户" } |
(2)添加内容弹窗
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
<template> <div> <el-form :model= "forms" :rules= "rules" ref= "ruleForm" label-width= "100px" > <el-form-item label= "登录名" prop= "loginName" > <el-input v-model= "forms.loginName" placeholder= "请输入登录名" ></el-input> </el-form-item> <el-form-item label= "昵称" prop= "name" > <el-input v-model= "forms.name" placeholder= "请输入昵称" ></el-input> </el-form-item> <el-form-item label= "密码" prop= "password" > <el-input v-model= "forms.password" placeholder= "请输入密码" show-password></el-input> </el-form-item> <el-form-item label= "邮箱" prop= "email" > <el-input v-model= "forms.email" placeholder= "请输入邮箱" ></el-input> </el-form-item> <el-form-item label= "手机号" prop= "phone" > <el-input v-model= "forms.phone" placeholder= "请输入手机号" ></el-input> </el-form-item> <el-form-item label= "头像" prop= "imgobj" > </el-form-item> <el-form-item> <el-button size= "small" type= "primary" plain @click= "save" >保存</el-button> </el-form-item> </el-form> </div> </template> <script> export default { name: 'AdminEdit' , props:{ show:{ type: Boolean } }, data(){ return { forms: { loginName: '' , name: '' , password: '' , email: '' , phone: '' , imgobj: '这是一张图片' }, rules:{ loginName:[ {required: true , message: '请输入登录名' , trigger: 'blur' }, {min : 1, max: 20, message: '长度在1-20之间' , trigger: 'change' } ], name:[ {required: true , message: '请输入昵称' , trigger: 'blur' }, {min : 1, max: 20, message: '长度在1-20之间' , trigger: 'change' } ], password:[ {required: true , message: '请输入密码' , trigger: 'blur' }, {min : 1, max: 100, message: '长度在1-100之间' , trigger: 'change' } ], email:[ {required: true , message: '请输入邮箱' , trigger: 'blur' }, {min : 1, max: 50, message: '长度在1-50之间' , trigger: 'change' }, {type: 'email' , message: '请输入正确格式的邮箱' , trigger: 'blur' } ], phone:[ {required: true , message: '请输入电话号' , trigger: 'blur' }, {min : 1, max: 20, message: '长度在1-20之间' , trigger: 'change' }, {pattern: /^1([38][0-9]|4[5-9]|5[0-3,5-9]|66|7[0-8]|9[89])[0-9]{8}$/, message: '请输入正确的手机号' , trigger: 'blur' } ], } } }, methods:{ save() { //提交表单前需要对表单再次进行验证 //获取表单对象 //表单二次验证 this .$refs[ 'ruleForm' ].validate((flag) => { //如果通过验证,则进行表单数据提交 if (flag === true ) { this .request( '/umsadmin/add' , 'post' , this .forms, response => { this .$message.success(response.message) }) } }) }, changeimg(file, fileList) { this .forms.imgobj = file.raw }, removeimg() { this .forms.imgobj = null } } } </script> <style> </style> |
2、此时前端给后端发post请求会出现跨域错误
跨域错误解决需要在后端植入跨域过滤器(Bean节点)
1
2
3
4
5
6
7
8
9
10
11
12
|
//跨域问题解决 @Bean CorsFilter getCorsFilter() { UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource(); CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedHeader( "*" ); corsConfiguration.addAllowedMethod( "*" ); corsConfiguration.addAllowedOrigin( "*" ); //域名 configurationSource.registerCorsConfiguration( "/**" , corsConfiguration); return new CorsFilter(configurationSource); } |
到此这篇关于SpringBoot+Vue实现数据添加功能的文章就介绍到这了,更多相关SpringBoot Vue数据添加内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/weixin_42067873/article/details/114728954