SpringBoot+Vue實(shí)現(xiàn)數(shù)據(jù)添加功能
一、添加代碼生成器
用來(lái)自動(dòng)為數(shù)據(jù)庫(kù)映射類(lèi)建立:mapper、service、controller
注:代碼生成器的寫(xiě)法,參考官方文檔:https://mp.baomidou.com/
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();
//這樣獲取到的是父項(xiàng)目的目錄
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); 實(shí)體屬性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 數(shù)據(jù)源配置
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"); //設(shè)置父包
//自定義生成路徑
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"); //實(shí)體類(lèi)
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);
//生成時(shí),繼承的父類(lèi)
strategy.setSuperEntityClass(BasePojo.class);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父類(lèi)
strategy.setSuperControllerClass("你自己的父類(lèi)控制器,沒(méi)有就不用設(shè)置!");
// 寫(xiě)于父類(lèi)中的公共字段
strategy.setSuperEntityColumns("id");
strategy.setInclude("ums_admin");
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
二、導(dǎo)入需要的jar包
前期需要導(dǎo)入的包有:mybatis-plus、mysql、duracloud(工具包)、pojo、spring-boot-starter-web
<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>
三、創(chuàng)建啟動(dòng)類(lèi)
啟動(dòng)類(lèi)必須創(chuàng)建在父包下面,注意在SpringBoot中,并不是不掃包,而是框架幫助完成了這件事,它會(huì)掃描啟動(dòng)類(lèi)所在包下的所有類(lèi)及其子包中的類(lèi)
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);
}
}
四、創(chuàng)建配置文件(application.yml)
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 #運(yùn)行的過(guò)程中輸出sql語(yǔ)句(日志信息) logging: level: com.hanmh.mapper: debug
五、返回值統(tǒng)一定義
1、ResultJson
package com.hanmh.pojo;
import lombok.Data;
@Data
public class ResultJson {
private Integer code; //200成功,500錯(cuò)誤
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種返回代號(hào)和返回信息,使用枚舉類(lèi)進(jìn)行實(shí)現(xiàn)
package com.hanmh.pojo;
import lombok.Data;
import lombok.Getter;
@Getter
public enum ResultCode {
SUCCESS(200, "請(qǐng)求成功"),
ERROR(500, "請(qǐng)求失敗"),
NOAUTH(401, "用戶(hù)未登錄或者登錄超時(shí)"), //操作時(shí)
NOPREMISSION(403, "沒(méi)有此權(quán)限");
private Integer code;
private String message;
//枚舉類(lèi)型的構(gòu)造默認(rèn)為私有
private ResultCode(Integer code, String message) {
this.code = code;
this.message = message;
}
}
六、創(chuàng)建基礎(chǔ)pojo
在所有的數(shù)據(jù)庫(kù)表種,共有的字段是ID,現(xiàn)在將id獨(dú)立出來(lái)
1、導(dǎo)入 mybatis-plus-annotation包
為了使用該包內(nèi)部的IdType等類(lèi)內(nèi)部提供的注解,以告訴BasePojo中某些字段在數(shù)據(jù)庫(kù)表中的存在與否
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-annotation</artifactId> <version>3.0-RELEASE</version> </dependency>
2、BasePojo類(lèi)
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;
//做分頁(yè)操作需要的字段
@TableField(exist = false)
private Integer pageNO;
@TableField(exist = false)
private Integer pageSize;
}
七、后端添加數(shù)據(jù)
1、密碼加密
(1)需要使用安全包提供加密服務(wù)(security)
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> </dependency>
2、將加密類(lèi)(BCryptPasswordEncoder)放入IOC容器
在SpringBoot環(huán)節(jié),需要將某個(gè)類(lèi)加入IOC容器,就需要在配置類(lèi)中,配置@Bean節(jié)點(diǎn)
@Configuration
public class AdminConfig {
@Bean
//將BCryptPasswordEncoder放進(jìn)IOC容器
BCryptPasswordEncoder getPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
注:使用此方法對(duì)數(shù)據(jù)進(jìn)行加密的原因:此加密方法相同明文密碼多次可以生成不同的密文,而MD5相同密碼則會(huì)生成相同的密文
3、后端添加數(shù)據(jù)簡(jiǎn)單實(shí)現(xiàn)
@PostMapping("/add")
ResultJson add(UmsAdmin umsAdmin) throws InterruptedException, IOException {
//對(duì)密碼加密
umsAdmin.setPassword(passwordEncoder.encode(umsAdmin.getPassword()));
//TimeUnit.SECONDS.sleep(2);
return ResultJson.success(adminService.save(umsAdmin), "添加用戶(hù)成功");
}
八、前端頁(yè)面添加功能
1、添加用戶(hù)(按鈕和彈窗)
<el-button>:elementUI按鈕標(biāo)簽 <el-button type="primary" plain @click="add">添加用戶(hù)</el-button> <!-- <el-dialog> 代表彈窗 :visible.sync表示顯示或隱藏--> <!-- close-on-click-modal代表點(diǎn)擊對(duì)話框以外區(qū)域是否可以關(guān)閉 --> <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)添加用戶(hù)功能
add() {
this.dialog.show = true
this.dialog.title = "添加用戶(hù)"
}
(2)添加內(nèi)容彈窗
<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="請(qǐng)輸入登錄名"></el-input>
</el-form-item>
<el-form-item label="昵稱(chēng)" prop="name">
<el-input v-model="forms.name" placeholder="請(qǐng)輸入昵稱(chēng)"></el-input>
</el-form-item>
<el-form-item label="密碼" prop="password">
<el-input v-model="forms.password" placeholder="請(qǐng)輸入密碼" show-password></el-input>
</el-form-item>
<el-form-item label="郵箱" prop="email">
<el-input v-model="forms.email" placeholder="請(qǐng)輸入郵箱"></el-input>
</el-form-item>
<el-form-item label="手機(jī)號(hào)" prop="phone">
<el-input v-model="forms.phone" placeholder="請(qǐng)輸入手機(jī)號(hào)"></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: '請(qǐng)輸入登錄名', trigger: 'blur'},
{min : 1, max: 20, message: '長(zhǎng)度在1-20之間', trigger: 'change'}
],
name:[
{required: true, message: '請(qǐng)輸入昵稱(chēng)', trigger: 'blur'},
{min : 1, max: 20, message: '長(zhǎng)度在1-20之間', trigger: 'change'}
],
password:[
{required: true, message: '請(qǐng)輸入密碼', trigger: 'blur'},
{min : 1, max: 100, message: '長(zhǎng)度在1-100之間', trigger: 'change'}
],
email:[
{required: true, message: '請(qǐng)輸入郵箱', trigger: 'blur'},
{min : 1, max: 50, message: '長(zhǎng)度在1-50之間', trigger: 'change'},
{type: 'email', message: '請(qǐng)輸入正確格式的郵箱', trigger: 'blur'}
],
phone:[
{required: true, message: '請(qǐng)輸入電話號(hào)', trigger: 'blur'},
{min : 1, max: 20, message: '長(zhǎng)度在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: '請(qǐng)輸入正確的手機(jī)號(hào)', trigger: 'blur'}
],
}
}
},
methods:{
save() {
//提交表單前需要對(duì)表單再次進(jìn)行驗(yàn)證
//獲取表單對(duì)象
//表單二次驗(yàn)證
this.$refs['ruleForm'].validate((flag) => {
//如果通過(guò)驗(yàn)證,則進(jìn)行表單數(shù)據(jù)提交
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、此時(shí)前端給后端發(fā)post請(qǐng)求會(huì)出現(xiàn)跨域錯(cuò)誤
跨域錯(cuò)誤解決需要在后端植入跨域過(guò)濾器(Bean節(jié)點(diǎn))
//跨域問(wèn)題解決
@Bean
CorsFilter getCorsFilter() {
UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*"); //域名
configurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(configurationSource);
}
到此這篇關(guān)于SpringBoot+Vue實(shí)現(xiàn)數(shù)據(jù)添加功能的文章就介紹到這了,更多相關(guān)SpringBoot Vue數(shù)據(jù)添加內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Vue2.0/3.0雙向數(shù)據(jù)綁定的實(shí)現(xiàn)原理詳解
- 關(guān)于vuex強(qiáng)刷數(shù)據(jù)丟失問(wèn)題解析
- Vue 如何追蹤數(shù)據(jù)變化
- vue+canvas實(shí)現(xiàn)數(shù)據(jù)實(shí)時(shí)從上到下刷新瀑布圖效果(類(lèi)似QT的)
- vue 數(shù)據(jù)(data)賦值問(wèn)題的解決方案
- Vue 重置data的數(shù)據(jù)為初始狀態(tài)操作
- Vue組件傳值過(guò)程中丟失數(shù)據(jù)的分析與解決方案
- 手寫(xiě)Vue2.0 數(shù)據(jù)劫持的示例
- vue 數(shù)據(jù)雙向綁定的實(shí)現(xiàn)方法
- Vue中避免濫用this去讀取data中數(shù)據(jù)
- 用vue設(shè)計(jì)一個(gè)數(shù)據(jù)采集器
相關(guān)文章
idea進(jìn)程結(jié)束但是項(xiàng)目頁(yè)面正常運(yùn)行怎么辦
這篇文章主要介紹了idea進(jìn)程結(jié)束但是項(xiàng)目頁(yè)面正常運(yùn)行怎么辦,很多朋友遇到這樣的情況不知道該如何解決了,下面小編給大家?guī)?lái)了idea進(jìn)程結(jié)束但是項(xiàng)目頁(yè)面正常運(yùn)行的解決方法,需要的朋友可以參考下2023-03-03
基于JSON實(shí)現(xiàn)傳輸byte數(shù)組過(guò)程解析
這篇文章主要介紹了基于JSON實(shí)現(xiàn)傳輸byte數(shù)組過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06
JavaWeb中JavaMail創(chuàng)建郵件和發(fā)送郵件
這篇文章主要介紹了JavaWeb中JavaMail創(chuàng)建郵件和發(fā)送郵件,較為詳細(xì)的分析了JavaMail發(fā)送郵件的用法,是非常實(shí)用的技巧,需要的朋友可以參考下2015-12-12
Java實(shí)現(xiàn)簡(jiǎn)單小畫(huà)板
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)簡(jiǎn)單小畫(huà)板,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06
Java開(kāi)發(fā)如何把數(shù)據(jù)庫(kù)里的未付款訂單改成已付款
這篇文章主要介紹了Java開(kāi)發(fā)如何把數(shù)據(jù)庫(kù)里的未付款訂單改成已付款,先介紹MD5算法,簡(jiǎn)單的來(lái)說(shuō),MD5能把任意大小、長(zhǎng)度的數(shù)據(jù)轉(zhuǎn)換成固定長(zhǎng)度的一串字符,實(shí)現(xiàn)思路非常簡(jiǎn)單需要的朋友可以參考下2022-11-11
JAVA 實(shí)現(xiàn)磁盤(pán)文件加解密操作的示例代碼
這篇文章主要介紹了JAVA 實(shí)現(xiàn)磁盤(pán)文件加解密操作的示例代碼,幫助大家利用Java實(shí)現(xiàn)文件的加解密,感興趣的朋友可以了解下2020-09-09

