springboot+elementUI

发布时间 2023-06-14 22:22:45作者: wn_garden

功能简介

后端用springboot实现数据库的增删改查,前端用vue中的element UI编写,实现简单的数据展示和增删改。

环境准备

1.vue环境
vue安装:https://www.cnblogs.com/xiaozhaoboke/p/16888421.html
安装好后打开vue ui

进入项目管理器,创建项目





添加elementUI插件和axios插件

2.后端springboot环境准备

后端实现

结构

entity层---数据库实例对象
dao层 --- 数据库操作层Mapper接口类
service层---业务接口以及实现类
controller层---路由
config层---解决跨域问题
application.yaml配置文件---配置端口和数据库连接信息

实例类对象

package com.wning.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;

import java.util.Date;
@Data
public class Customer {
    private String identity;
    private String custname;
    private Integer sex;
    private String address;
    private String phone;
    private String career;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss" ,timezone = "GMT+8")
    private Date createtime;
}

mapper接口类

package com.wning.dao;

import com.wning.entity.Customer;

import java.util.List;

public interface CustomerMapper {

    List<Customer> findAll();

    Customer findByIdentity(String identity);

    Integer addCustomer(Customer customer);

    Integer updateCustomer(Customer customer);

    Integer deleteCustomer(String identity);


}

mapper文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wning.dao.CustomerMapper">
    <!--    查询-->
    <select id="findAll" resultType="com.wning.entity.Customer">
        select * from t_customer;
    </select>
    <!--    查询-->
    <select id="findByIdentity" resultType="com.wning.entity.Customer">
        select * from t_customer where identity=#{identity}
    </select>
    <!--    添加用户-->
    <insert id="addCustomer" parameterType="com.wning.entity.Customer">
        insert into t_customer
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="identity != null">
                identity,
            </if>
            <if test="custname != null">
                custname,
            </if>
            <if test="sex != null">
                sex,
            </if>
            <if test="address != null">
                address,
            </if>
            <if test="phone != null">
                phone,
            </if>
            <if test="career != null">
                career,
            </if>
            <if test="createtime != null">
                createtime,
            </if>
        </trim>
        <trim prefix="values(" suffix=")" suffixOverrides=",">
            <if test="identity != null">
                #{identity},
            </if>
            <if test="custname != null">
                #{custname},
            </if>
            <if test="sex != null">
                #{sex},
            </if>
            <if test="address != null">
                #{address},
            </if>
            <if test="phone != null">
                #{phone},
            </if>
            <if test="career != null">
                #{career},
            </if>
            <if test="createtime != null">
                #{createtime},
            </if>
        </trim>
    </insert>
<!--    修改客户-->
    <update id="updateCustomer">
        update t_customer
        <set>
            <if test="custname != null">
                custname=#{custname},
            </if>
            <if test="sex != null">
                sex=#{sex},
            </if>
            <if test="address != null">
                address=#{address},
            </if>
            <if test="phone != null">
                phone=#{phone},
            </if>
            <if test="career != null">
                career=#{career},
            </if>
        </set>
        where identity = #{identity}
    </update>
<!--    删除-->
    <delete id="deleteCustomer">
        delete from t_customer where identity = #{identity}
    </delete>
</mapper>

service层

package com.wning.service;

import com.wning.entity.Customer;

import java.util.List;

public interface CustomerService {

    List<Customer> findAll();

    Customer findByIdentity(String identity);

    Integer addCustomer(Customer customer);

    Integer updateCustomer(Customer customer);

    Integer deleteCustomer(String identity);
}

service实现类

package com.wning.service;

import com.wning.dao.CustomerMapper;
import com.wning.entity.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CustomerServiceImpl implements  CustomerService{

    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public List<Customer> findAll() {
        return customerMapper.findAll();
    }

    @Override
    public Customer findByIdentity(String identity) {
        return customerMapper.findByIdentity(identity);
    }

    @Override
    public Integer addCustomer(Customer customer) {
        customer.setCreatetime(new Date());
        return customerMapper.addCustomer(customer);
    }

    @Override
    public Integer updateCustomer(Customer customer) {
        return customerMapper.updateCustomer(customer);
    }

    @Override
    public Integer deleteCustomer(String identity) {
        return customerMapper.deleteCustomer(identity);
    }
}

controller层

package com.wning.contorller;

import com.wning.entity.Customer;
import com.wning.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/customer")
public class CustomerController {

    @Autowired
    CustomerService customerService;

    @GetMapping
    public List<Customer> findAll(){
        return customerService.findAll();
    }

    @GetMapping("/{identity}")
    public Customer findByIdentity(@PathVariable("identity") String  identity){
        System.out.println(identity);
        return customerService.findByIdentity(identity);
    }

    @PostMapping
    public Integer addCustomer(@RequestBody Customer customer){
        return customerService.addCustomer(customer);
    }

    @PutMapping
    public Integer updateCustomer(@RequestBody Customer customer){
        return customerService.updateCustomer(customer);
    }

    @DeleteMapping
    public Integer deleteCustomer(@RequestParam String  identity){
        return customerService.deleteCustomer(identity);
    }


}

config层

package com.wning.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 解决前端访问后后端接口的【跨域问题】
 */
@Configuration
public class CrosConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .allowCredentials(true)
                .allowedHeaders("*")
                .maxAge(3600);
    }
}

配置文件

server:
  port: 80

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/testdb2?serverTimezone=UTC
    username: root
    password: 123456
    type: com.alibaba.druid.pool.DruidDataSource
  main:
    allow-circular-references: true

mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml

记得在主执行方法中扫描dao层

前端实现

结构

plugins插件--有axios和element
router--配置路由
views--页面显示


App.vue文件

index.js路由配置

展示页面,用element中的表格展示+button按钮。

<template>
  <div>
    <el-row>
      <el-col :span="16" style="float: left;">
        <el-button  plain type="primary" icon="el-icon-edit" @click="addCustomer()">录入信息</el-button>
      </el-col>

      <el-col :span="8" style="float: right;">
        <el-input style="width:75%;" v-model="inputIdentity" placeholder="请输入内容"></el-input>
        <el-button style="width:25%;" plain type="success" icon="el-icon-search" @click="findByIdentity()">查询</el-button>
      </el-col>
    </el-row>

    <br>
    <el-table border :data="tableData" style="width: 100%" :default-sort = "{prop: 'date', order: 'descending'}">

      <el-table-column
          prop="createtime"
          label="入职日期"
          sortable
          width="200">
      </el-table-column>
      <el-table-column
          prop="custname"
          label="姓名"
          width="100">
      </el-table-column>

      <el-table-column
          prop="sex"
          label="性别"
          sortable
          width="100">
        <template v-slot="scope">
          <span v-if="scope.row.sex===1">男</span>
          <span v-if="scope.row.sex===0">女</span>
        </template>
      </el-table-column>

      <el-table-column
          prop="career"
          label="岗位"
          sortable
          width="120">
      </el-table-column>
      <el-table-column
          prop="phone"
          label="电话"
          width="120">
      </el-table-column>
      <el-table-column
          prop="address"
          label="地址"
          :formatter="formatter">
      </el-table-column>
      <el-table-column
          prop="identity"
          label="身份证号"
          width="180">
      </el-table-column>

      <el-table-column
          label="操作"
          width="160">
        <template v-slot="scope">
          <el-button
              size="mini"
              @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name: "Index",
  created(){
    let _this=this
    axios.get('http://localhost/customer/')
        .then(function (resp){
          _this.tableData=resp.data
        })
  },
  data(){
    return{
      tableData:"",
      inputIdentity:""
    }
  },
  methods: {
    formatter(row, column) {
      return row.address;
    },
    addCustomer(){
      this.$router.push("/Add")
    },
    findByIdentity(){
      if(this.inputIdentity){
        let _this=this
        axios.get("http://localhost/customer/"+this.inputIdentity).then(function (resp){
          _this.tableData=[resp.data]
        })}
      else{location.reload()}
      },
    handleEdit(row){
      this.$router.push('/update?identity='+row.identity)
    },
    handleDelete(row) {
      this.$confirm('删除【'+row.custname+'】相关数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let _this=this
        axios.delete('http://localhost/customer/?identity='+row.identity).then(function (resp){
          //删除成功,返回删除个数1
          if(resp.data >0 ){
            _this.$message({
              type: 'success',
              message: '删除成功!'
            })
            //延时1秒 加载页面
            setTimeout(()=>{
              location.reload()
            },1000)
          }else {
            //删除失败提示
            _this.$message({
              type: 'error',
              message: '删除失败!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>

<style scoped>

</style>

更新页面,用element中的表单实现。

<template>
  <div style="width:50%;">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item  label="身份证号" prop="identity" >
        <el-input readonly  v-model="ruleForm.identity"></el-input>
      </el-form-item>

      <el-form-item label="名字" prop="custname">
        <el-input v-model="ruleForm.custname"></el-input>
      </el-form-item>

      <el-form-item label="性别" prop="resource">
        <el-radio-group v-model="ruleForm.sex">
          <el-radio :label=1>男</el-radio>
          <el-radio :label=0>女</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="岗位" prop="career">
        <el-input v-model="ruleForm.career"></el-input>
      </el-form-item>

      <el-form-item label="地址" >
        <el-input type="textarea" v-model="ruleForm.address"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">立即修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name:"Update",
  created() {
    let _this=this
    axios.get("http://localhost/customer/"+this.$route.query.identity).then(function (resp){
      _this.ruleForm=resp.data
    })
  },
  data() {
    return {
      ruleForm: {
        identity: '',
        custname: '',
        sex: 1,
        career:'',
        address:''
      },
      rules: {
        custname: [
          { required: true, message: '请输入名称', trigger: 'change' }
        ],
        career: [
          { required: true, message: '请选输入岗位', trigger: 'change' }
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      let _this=this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios.put('http://localhost/customer/',this.ruleForm).then(function (resp){
            if(resp.data >0){
              _this.$alert('修改成功!','信息变更',{
                confirmButtonText:'确定',
                callback:action => {
                  _this.$router.push('/index')
                }
              });
            }else {
              alert('修改失败')
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
}
</script>

<style scoped>

</style>

add页面和更新页面一样

<template>
  <div style="width:50%;">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item  label="身份证号" prop="identity" >
        <el-input  v-model="ruleForm.identity"></el-input>
      </el-form-item>

      <el-form-item label="名字" prop="custname">
        <el-input v-model="ruleForm.custname"></el-input>
      </el-form-item>

      <el-form-item label="性别" prop="resource">
        <el-radio-group v-model="ruleForm.sex">
          <el-radio :label=1>男</el-radio>
          <el-radio :label=0>女</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="岗位" prop="career">
        <el-input v-model="ruleForm.career"></el-input>
      </el-form-item>

      <el-form-item label="电话" prop="career">
        <el-input v-model="ruleForm.phone"></el-input>
      </el-form-item>

      <el-form-item label="地址" >
        <el-input type="textarea" v-model="ruleForm.address"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">立即添加</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name:"Add",
  data() {
    return {
      ruleForm: {
        identity: '',
        custname: '',
        sex: 1,
        career:'',
        phone:'',
        address:''
      },
      rules: {
        identity: [
          { required: true, message: '身份证号不能为空', trigger: 'change' },
          { min: 18, max: 18, message: '请输入18位身份证号', trigger: 'blur' }
        ],
        custname: [
          { required: true, message: '请输入名称', trigger: 'change' }
        ],
        career: [
          { required: true, message: '请选输入岗位', trigger: 'change' }
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      let _this=this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios.post('http://localhost/customer/',this.ruleForm).then(function (resp){
            if(resp.data >0){
              _this.$alert('添加成功!','员工录入',{
                confirmButtonText:'确定',
                callback:action => {
                  _this.$router.push('/index')
                }
              });
            }else {
              _this.$alert('添加成功!','员工录入',{confirmButtonText:'确定'})
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
}
</script>

<style scoped>

</style>

前端用axios发请求

// 查询接口
findByIdentity(){
      if(this.inputIdentity){
        let _this=this
        axios.get("http://localhost/customer/"+this.inputIdentity).then(function (resp){
          _this.tableData=[resp.data]
        })}
      else{location.reload()}
      }

//静态页面跳转
handleEdit(row){
      this.$router.push('/update?identity='+row.identity)
    }

// 发送delete请求
 axios.delete('http://localhost/customer/?identity='+row.identity).then(function (resp){
  console.log(resp.data)
})

//发送put请求
submitForm(formName) {
      let _this=this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios.put('http://localhost/customer/',this.ruleForm).then(function (resp){
            if(resp.data >0){
              _this.$alert('修改成功!','信息变更',{
                confirmButtonText:'确定',
                callback:action => {
                  _this.$router.push('/index')
                }
              });
            }else {
              alert('修改失败')
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });

//发送update请求
submitForm(formName) {
      let _this=this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios.post('http://localhost/customer/',this.ruleForm).then(function (resp){
            if(resp.data >0){
              _this.$alert('添加成功!','员工录入',{
                confirmButtonText:'确定',
                callback:action => {
                  _this.$router.push('/index')
                }
              });
            }else {
              _this.$alert('添加成功!','员工录入',{confirmButtonText:'确定'})
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });