SpringBoot+Vue实现数据添加功能

一、添加代码生成器

用来自动为数据库映射类建立:mapper、service、controller

注:代码生成器的写法,参考官方文档: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();
    //这样获取到的是父项目的目录
    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

<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中,并不是不扫包,而是框架帮助完成了这件事,它会扫描启动类所在包下的所有类及其子包中的类

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)

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

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种返回代号和返回信息,使用枚举类进行实现

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中某些字段在数据库表中的存在与否

<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-annotation</artifactId>
  <version>3.0-RELEASE</version>
</dependency>

2、BasePojo类

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)

<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-core</artifactId>
</dependency>

2、将加密类(BCryptPasswordEncoder)放入IOC容器

在SpringBoot环节,需要将某个类加入IOC容器,就需要在配置类中,配置@Bean节点

@Configuration
public class AdminConfig {
  @Bean
  //将BCryptPasswordEncoder放进IOC容器
  BCryptPasswordEncoder getPasswordEncoder() {
    return new BCryptPasswordEncoder();
  }
}

注:使用此方法对数据进行加密的原因:此加密方法相同明文密码多次可以生成不同的密文,而MD5相同密码则会生成相同的密文

3、后端添加数据简单实现

@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、添加用户(按钮和弹窗)

<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)添加用户功能

add() {
 this.dialog.show = true
 this.dialog.title = "添加用户"
}

(2)添加内容弹窗

<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节点)

//跨域问题解决
@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数据添加内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • 部署vue+Springboot前后端分离项目的步骤实现

    单页应用 vue经常被用来开发单页应用(SinglePage Web Application,SPA),什么叫做单页应用呢,也就是只有一张web页面的应用,单页应用的跳转只需要刷新局部资源,大大加快的了我们页面的响应速度 前端页面打包 打开vue工程,在项目根目录下创建一个配置文件:vue.config.js,然后在里面写入以下内容: module.exports = { assetsDir: 'static', // 静态资源保存路径 outputDir: 'dist', // 打包后生成的文

  • Spring boot 和Vue开发中CORS跨域问题解决

    跨域资源共享CORS(Cross-origin Resource Sharing),是W3C的一个标准,允许浏览器向跨源的服务器发起XMLHttpRequest请求,克服ajax请求只能同源使用的限制.关于CORS的详细解读,可参考阮一峰大神的博客:跨域资源共享CORS详解. 1. 遇到的问题: 我用spring-boot 做Rest服务,Vue做前端框架,用了element-admin-ui这个框架做后台管理.在调试的过程中遇到了如下错误: Preflight response is not

  • springboot整合vue实现上传下载文件

    springboot整合vue实现上传下载文件,供大家参考,具体内容如下 环境 springboot 1.5.x 完整代码下载:springboot整合vue实现上传下载 1.上传下载文件api文件 设置上传路径,如例子: private final static String rootPath = System.getProperty("user.home")+File.separator+fileDir+File.separator; api接口: 下载url示例:http://l

  • spring boot+vue 的前后端分离与合并方案实例详解

    springboot和vue结合的方案网络上的主要有以下两种: 1. [不推荐]在html中直接使用script标签引入vue和一些常用的组件,这种方式和以前传统的开发是一样的,只是可以很爽的使用vue的双向数据绑定,这种方式只适合于普通的全栈开发. 2.[推荐]使用vue官方的脚手架创建单独的前端工程项目,做到和后端完全独立开发和部署,后端单独部署一个纯restful的服务,而前端直接采用nginx来部署,这种称为完全的前后端分离架构开发模式,但是在分离中有很多api权限的问题需要解决,包括部

  • vue+springboot前后端分离实现单点登录跨域问题解决方法

    最近在做一个后台管理系统,前端是用时下火热的vue.js,后台是基于springboot的.因为后台系统没有登录功能,但是公司要求统一登录,登录认证统一使用.net项目组的认证系统.那就意味着做单点登录咯,至于不知道什么是单点登录的同学,建议去找一下万能的度娘. 刚接到这个需求的时候,老夫心里便不屑的认为:区区登录何足挂齿,但是,开发的过程狠狠的打了我一巴掌(火辣辣的一巴掌)...,所以这次必须得好好记录一下这次教训,以免以后再踩这样的坑. 我面临的第一个问题是跨域,浏览器控制台直接报CORS,

  • 解决前后端分离 vue+springboot 跨域 session+cookie失效问题

    环境: 前端 vue ip地址:192.168.1.205 后端 springboot2.0 ip地址:192.168.1.217 主要开发后端. 问题: 首先登陆成功时将用户存在session中,后续请求在将用户从session中取出检查.后续请求取出的用户都为null. 解决过程: 首先发现sessionID不一致,导致每一次都是新的会话,当然不可能存在用户了.然后发现cookie浏览器不能自动保存,服务器响应set-cookie了 搜索问题,发现跨域,服务器响应的setCookie浏览器无

  • Springboot项目与vue项目整合打包的实现方式

    我的环境 * JDK 1.8  * maven 3.6.0  * node环境 1.为什么需要前后端项目开发时分离,部署时合并? 在一些公司,部署实施人员的技术无法和互联网公司的运维团队相比,由于各种不定的环境也无法做到自动构建,容器化部署等.因此在这种情况下尽量减少部署时的服务软件需求,打出的包数量也尽量少.针对这种情况这里采用的在开发中做到前后端独立开发,打包时在后端springboot打包发布时将前端的构建输出一起打入,最后只需部署springboot的项目即可,无需再安装nginx服务器

  • vue+springboot实现项目的CORS跨域请求

    跨域资源共享CORS(Cross-origin Resource Sharing),是W3C的一个标准,允许浏览器向跨源的服务器发起XMLHttpRequest请求,克服ajax请求只能同源使用的限制.关于CORS的详细解读,可参考阮一峰大神的博客:跨域资源共享CORS详解.本文为通过一个小demo对该博客中分析内容的一些验证. 1.springboot+vue项目的构建和启动 细节不在此赘述,任何简单的springboot项目就可以,而前端vue项目只需用axios发ajax请求即可. 我的d

  • SpringBoot+Vue实现数据添加功能

    一.添加代码生成器 用来自动为数据库映射类建立:mapper.service.controller 注:代码生成器的写法,参考官方文档:https://mp.baomidou.com/ package com.hanmh.utils; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomido

  • springboot vue接口测试定义编辑功能的实现

    目录 基于springboot+vue 的测试平台开发 一.后端 1. 查询接口 2. 更新接口 二.前端 1. 实现编辑外显 2. 实现接口更新 基于springboot+vue 的测试平台开发 继续更新 额,昨天还说编辑不着急做,但是我发现如果不做,那么在做接口发送功能的时候,我需要反复新增新的接口来调试,那就先做了. 一.后端 后端要增加2个接口:根据接口ID查询.更新接口. 1. 查询接口 @GetMapping("/getApi") public Result getApiB

  • Springboot Vue实现单点登陆功能示例详解

    目录 正文 简单上个图 先分析下登陆要做啥 怎么落实? 上代码 接口: token生成部分 刷新token 验证token 正文 登陆是系统最基础的功能之一.这么长时间了,一直在写业务,这个基础功能反而没怎么好好研究,都忘差不多了.今天没事儿就来撸一下. 以目前在接触和学习的一个开源系统为例,来分析一下登陆该怎么做.代码的话我就直接CV了. 简单上个图 (有水印.因为穷所以没开会员) 先分析下登陆要做啥 首先,搞清楚要做什么. 登陆了,系统就知道这是谁,他有什么权限,可以给他开放些什么业务功能,

  • SpringBoot+VUE实现数据表格的实战

    目录 前言 使用的开发工具: 一.前端准备 1. 基础界面 2. 导入JS文件 二.后端准备 1. 创建实体类 2. Controller层 3. Service层 4. Mapper层 三.前后端整合 四.运行结果 总结 前言 还记得第一次做项目时,因为不会将数据库表中的数据渲染到前端而头疼,最后还是靠layui提供的数据表格API实现了前端数据表格的渲染.一直到现在做了很多SpringBoot项目.SSM项目之后,现在返回头来看这个曾经这个让我备受折磨的问题,脑海中下意识就会想到很多种解决的

  • springboot中validator数据校验功能的实现

    普通校验 导入依赖: 默认的报错:没有提示具体的属性 设置自己的错误信息提示:创建 ValidationMessages.properties 内容如下: user.id.notnull = id 不能为空 user.username.size = username 长度为5-10 user.age.min = age 年龄最小为1 user.age.max = age 年龄最大为100 user.email.pattern= email 格式不正确 实体类注解上设置message属性,,使用{

  • 解决vue动态为数据添加新属性遇到的问题

    vue为数据添加属性时遇到的坑,通过self.book[i].['cur']=false;动态为数据添加属性时,数据变化了,但是视图没有发生更新. 具体原因不明白.... 解决方法:通过set来添加属性this.set来添加属性this.set(self.book[i],'cur',false); 这样子来设置,就没问题了 以上这篇解决vue动态为数据添加新属性遇到的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们.

  • springboot vue前后端接口测试树结点添加功能

    目录 基于springboot+vue的测试平台开发 一.前端Tree树形控件的append方法 二.后端实现节点新增接口 1. controller 层 2. service 层 三.前后端联调 四.编辑节点名称 1. 打开对话框 2. 新增节点 3. 测试 基于springboot+vue的测试平台开发 继续更新. 一.前端Tree树形控件的append方法 在elementUI 树控件下有个append方法,可以用来为 Tree 中的一个节点追加一个子节点. 目前我们已经完成了树列表的接口

  • springboot+vue实现登录功能

    本文实例为大家分享了springboot+vue实现登录功能的具体代码,供大家参考,具体内容如下 目录结构 前端端口:8080 后端端口:8900 login.vue <template> <div class="login_content"> <!-- 登录块 --> <div class="login_box"> <!-- 头像 --> <div class="avatar_box&qu

  • SpringBoot+Vue+Axios+BootStrap实现图书的增删改查功能示例

    目录 一.开发工具 二.项目结构 三.编写项目 四.运行项目 由于是初学Vue.Axios,可能在界面和功能上存在着一些问题,但这些并不妨碍使用.如果有对编程感兴趣的朋友,可以试着做一做.这个由于是第一次做,不太熟练.在后续的过程中会不断的完善. 一.开发工具 IntelliJ IDEA Ultimate 2021.1 apache-maven-3.5.4 MySQL5.7 JDK 1.8.0_281 二.项目结构 三.编写项目 1.创建数据库 SET NAMES utf8mb4; SET FO

  • springboot+vue组件开发实现接口断言功能

    目录 基于 springboot+vue 的测试平台 一.组件的关系 二.组件的开发 1. ApiAssertions 2. ApiAssertionsEdit 3. ApiAssertionJsonPath 基于 springboot+vue 的测试平台 (练手项目)开发继续更新. 接下来准备开发请求断言功能.关于这个功能要实现哪些需求,长什么样子,我参考了下其他优秀的业界工具,比如apifox.metersphere等. 于是决定还是先紧着最常用的来开发:JSONPath.响应时间.文本,而

随机推荐