首页 > 其他分享 >springboot+elementUI

springboot+elementUI

时间:2023-06-14 22:22:14浏览次数:58  
标签:customer return springboot elementUI resp import public identity

功能简介

后端用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;
        }
      });

标签:customer,return,springboot,elementUI,resp,import,public,identity
From: https://www.cnblogs.com/wn-garden/p/17481524.html

相关文章

  • springboot-feign接口压缩异常
    WARNorg.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver-Resolved[org.springframework.http.converter.HttpMessageNotReadableException:JSONparseerror:Illegalcharacter((CTRL-CHAR,code31)):onlyregularwhitespace(\r,\......
  • SpringBoot使用自定义的logback日志
    1.介绍描述:主要由三个模块构成logback-core:核心代码块(不介绍)logback-classic:实现了slf4j的api,加入该依赖可以实现log4j的api。logback-access:访问模块与servlet容器集成提供通过http来访问日志的功能(也就是说不需要访问服务器,直接在网页上就可以访问日志文件,实现HTTP访问......
  • SpringBoot使用自定义日志注解,配置切面
    1.使用技巧以下是需要注意的部分:在环绕通知中使用ProceedingJoinPoint,控制目标方法的运行。在其他通知类型中使用JoinPoint。如果使用JoinPoint则必须位于参数的第一位。ProceedingJoinPoint中有特殊的方法proceed()。当有多个切面时,使用@Order(11)来指定注解的优先级。......
  • 根据不同场景(是否需要连接数据库)启动SpringBoot
    1.场景描述描述:使用场景:项目中的一部分业务不需要进行数据库操作,当只使用这部分功能时,希望程序启动时可以不进行数据库的连接项目中需要数据库相关的业务时再进行配置注意:Springboot在启动时会根据pom.xml启动器来判断是否开启相应的自动配置解决方式:设置一个包......
  • vue+ elementUI
    1、在dos窗口下运行命令npmielement-ui-S安装elementui2、配置elementui3、画面代码展示登录页面<template><div><!--:是v-bind的简写--><el-formref="loginForm":model="form":rules="rules"label-width="80px&q......
  • 【SpringBoot】注解
    Controller-@RestController-@RequestMapping("/path")Controller内方法@GetMapping("/path/{xxx}")@PostMapping("/path")POST处理函数参数@RequestBody//将Json体参数值按照参数名传入类内对应字段中GET处理函数参数@PathVariable//按名称获取请求路径中的变......
  • 【React工作记录一百零五】springBoot+vue实现登录操作和JWT验证
    前言大家好我是歌谣今天继续进行前后端的一个学习目前进入的是javaweb部分今天来聊聊登录部分和JWT验证部分的书写用户登录loginControllerpackagecom.itheima.controller;importcom.itheima.pojo.Emp;importcom.itheima.pojo.Result;importcom.itheima.service.EmpSer......
  • webStorm添加elementui注解
    https://element.eleme.io  添加成功后的效果 ......
  • IDEA 退出 springboot 应用没有关闭
    使用idea发现的问题。当运行spring-boot:run启动项目后,在控制台关闭项目。再次启动项目,报错端口被占用  Addressalreadyinuse:bind。后发现虽然使用idea控制台关闭项目,但是实际上该项目依旧在运行中,只能通过kill进程id来解决。但是这种方式极不方便,总不能每次都......
  • 基于SpringBoot+MyBatis+Thymeleaf的学生管理系统搭建
    学生管理系统Maven工程搭建【步骤】:打开IDEA工具,选择创建一个新工程。选择SpringInitializr,点击Next按钮。大家也可以通过Spring提供的在线创建的方式创建工程,访问(https://start.spring.io),然后将创建后的工程代码zip包解压后,使用IDEA导入工程。这种方式不在本文描述......