要求:Spring Boot开发工具、MySQL、VScode(前端开发工具)以及云端服务器和Postman测试软件
后端(Spring Boot开发工具)
Dept.java
package com.newer.work2.pojo;
/**
* Dept实体类
* @author Admin
*
*/
public class Dept {
/**
* 编号
*/
int id;
/**
* 名称
*/
String name;
/**
* 所在地
*
*/
String loc;
// setters,gettters方法
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
//tostring方法
@Override
public String toString() {
return "Dept [id=" + id + ", name=" + name + ", loc=" + loc + "]";
}
}
DeptMapper.java
package com.newer.work2.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.newer.work2.pojo.Dept;
/**
* MyBatis是sql的映射框架
* @author Admin
*
*/
@Mapper
public interface DeptMapper {
/**
* Dept表执行插入语句
*/
@Insert("insert into dept(name,loc) values(#{name},#{loc})")
void create(Dept dept);
/**
* Dept表执行查询操作
*/
@Select("select * from dept")
List<Dept>findAll();
/**
* Dept表根据id执行查询操作
*
*/
@Select("select * from dept where id=#{id}")
Dept findById(int id);
/**
* Dept 表执行更新操作
*/
@Update("update dept set name=#{name},loc=#{loc} where id=#{id}")
void update(Dept dept);
/**
* Dept 表执行删除操作
*/
@Delete("delete from dept where id=#{id} ")
void delete(int id);
}
DeptController.java
package com.newer.work2.controller;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.newer.work2.mapper.DeptMapper;
import com.newer.work2.pojo.Dept;
/**
* RESTful API接口
* @author Admin
*
*/
//启用跨域访问
@CrossOrigin
@RestController
@RequestMapping("/api/v1/dept")
public class DeptController {
/**
* 自动依赖注入
* @return
*/
@Autowired
DeptMapper deptmapper;
// Get
@GetMapping
public List<Dept> findAll() {
return deptmapper.findAll();
}
// Get id
@GetMapping("/{id}")
public Dept findById(@PathVariable int id) {
return deptmapper.findById(id);
}
// Post
@PostMapping
public void create(@RequestBody Dept dept) {
deptmapper.create(dept);
}
// Put id
@PutMapping("/{id}")
public void update(@PathVariable int id,@RequestBody Dept dept) {
// 设置更新数据的id
dept.setId(id);
deptmapper.update(dept);
}
// Delete id
@DeleteMapping("{id}")
public void delete(@PathVariable int id) {
deptmapper.delete(id);
}
}
Staff.java
package com.newer.work2.pojo;
/**'
* 实体类
* @author Admin
*
*/
public class Staff {
/**
* 编号
*/
int id;
/**
* 名字
*/
String name;
/**
* 职位
*/
String job;
/**
* 电话
*/
String phone;
// getters setters 方法
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
//tostring方法
@Override
public String toString() {
return "Staff [id=" + id + ", name=" + name + ", job=" + job + ", phone=" + phone + "]";
}
}
StaffMapper.java
package com.newer.work2.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.newer.work2.pojo.Staff;
/**
* 数据持久化储存
* MyBatis是SQL映射框架
* @author Admin
*
*/
@Mapper
public interface StaffMapper {
/**
* 表执行插入语句
* @param staff
*/
@Insert("insert into staff(name,job,phone) values(#{name},#{job},#{phone})")
void save(Staff staff);
/**
* 表执行查询语句
* @return
*/
@Select("select * from staff")
List<Staff>findAll();
/**
* 根据id从表执行查询语句
* @param id 查询的id
*
* @return
*/
@Select("select * from staff where id=#{id}")
Staff findById(int id);
/**
* 表执行更改功能
*
*/
@Update("update staff set name=#{name},job=#{job},phone=#{phone} where id=#{id}")
void update(Staff staff);
/**
* 表执行删除语句
*/
@Delete("delete from staff where id=#{id}")
void delete(int id);
}
StaffController.java
package com.newer.work2.controller;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.newer.work2.mapper.StaffMapper;
import com.newer.work2.pojo.Staff;
/**
*
* 定义RESTful API接口
* @author Admin
*
*/
//启用跨域访问
@CrossOrigin
@RestController
@RequestMapping("/api/v1/staff")
public class StaffController {
/**
* 依赖注入
*/
@Autowired
StaffMapper staffMapper;
// Get
@GetMapping
public List<Staff>findAll(){
return staffMapper.findAll();
}
// 通过id Get
// @PathVariable:路径变量
@GetMapping("/{id}")
public Staff findById(@PathVariable int id) {
return staffMapper.findById(id);
}
// Post
@PostMapping
public void create(@RequestBody Staff staff) {
staffMapper.save(staff);
}
// Put
@PutMapping("/{id}")
public void update(@PathVariable int id,@RequestBody Staff staff) {
staff.setId(id);
staffMapper.update(staff);
}
// Delete
@DeleteMapping("/{id}")
public void delete(@PathVariable int id) {
staffMapper.delete(id);
}
}
application.properties
#MySQL数据源
spring.datasource.url=jdbc:mysql://121.41.98.23:3306/test
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#显示日志信息
logging.level.web=debug
#显示详细信息
spring.http.log-request-details=true
#修改端口号
server.port=9000
前端(vscode):
vuex+vueCLI+axios+router
App.vue
<template>
<div>
<!-- 面包屑 -->
<nav class="breadcrumb">
<router-link class="breadcrumb-item" to="/">部门</router-link>
<router-link class="breadcrumb-item" to="/about">职员</router-link>
</nav>
<!-- 展板 -->
<div class="jumbotron jumbotron-fluid">
<router-view />
</div>
</div>
</template>
<style>
axios.js
"use strict";
import Vue from 'vue';
import axios from "axios";
// Full config: https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
let config = {
// baseURL: process.env.baseURL || process.env.apiUrl || ""
// timeout: 60 * 1000, // Timeout
// withCredentials: true, // Check cross-site Access-Control
};
const _axios = axios.create(config);
_axios.interceptors.request.use(
function(config) {
// Do something before request is sent
return config;
},
function(error) {
// Do something with request error
return Promise.reject(error);
}
);
// Add a response interceptor
_axios.interceptors.response.use(
function(response) {
// Do something with response data
return response;
},
function(error) {
// Do something with response error
return Promise.reject(error);
}
);
Plugin.install = function(Vue) {
Vue.axios = _axios;
window.axios = _axios;
Object.defineProperties(Vue.prototype, {
axios: {
get() {
return _axios;
}
},
$axios: {
get() {
return _axios;
}
},
});
};
Vue.use(Plugin)
export default Plugin;
index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component:About
}
]
const router = new VueRouter({
routes
})
export default router
Home.vue
// dept表
<template>
<div class="row">
<div class="col-lg-4 col-sm-12">
<!-- 表单 -->
<div class="form-group">
<label for>部门名称:</label>
<input
v-model="name"
type="text"
name
id
class="form-control"
placeholder
aria-describedby="helpId"
/>
</div>
<div class="form-group">
<label for>部门所在地:</label>
<input
v-model="loc"
type="text"
name
id
class="form-control"
placeholder
aria-describedby="helpId"
/>
</div>
<!-- 创建按钮 -->
<button @click="add()" type="button" name id class="btn btn-primary btn-lg btn-block">创建</button>
</div>
<div class="col-lg-8 col-sm-12">
<!-- 表格 -->
<table class="table">
<thead>
<tr>
<th>编号</th>
<th>名称</th>
<th>所在地</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(dept, index) in depts" :key="index">
<td>{{dept.id}}</td>
<td>{{dept.name}}</td>
<td>{{dept.loc}}</td>
<td>
<div class="row">
<button
@click="edit(index)"
type="button"
name
id
class="btn btn-primary mr-3"
data-toggle="modal"
data-target="#modelId"
>编辑</button>
<!-- 模态框 -->
<!-- Button trigger modal -->
<!-- <button type="button" class="btn btn-primary btn-lg">
Launch
</button>-->
<!-- Modal -->
<div
class="modal fade"
id="modelId"
tabindex="-1"
role="dialog"
aria-labelledby="modelTitleId"
aria-hidden="true"
>
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">请输入你要修改的部门信息:</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label for>部门编号:</label>
<input
v-model="editItem.id"
type="text"
name
id
class="form-control"
placeholder
aria-describedby="helpId"
/>
</div>
<div class="form-group">
<label for>部门名称:</label>
<input
v-model="editItem.name"
type="text"
name
id
class="form-control"
placeholder
aria-describedby="helpId"
/>
</div>
<div class="form-group">
<label for>部门所在地:</label>
<input
v-model=" editItem.loc"
type="text"
name
id
class="form-control"
placeholder
aria-describedby="helpId"
/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
<button
@click="update()"
type="button"
class="btn btn-primary"
data-dismiss="modal"
>确定</button>
</div>
</div>
</div>
</div>
<button @click="deletedept(dept.id)" type="button" name id class="btn btn-danger">删除</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script>
import { mapState, mapActions } from "vuex";
export default {
name: "Home",
data() {
return {
// 部门名称
name: "",
// 部门所在地
loc: "",
editIndex: 0,
editItem: {}
};
},
methods: {
...mapActions(["getdepts", "adddept", "deletedept","updatedept"]),
// 创建部门的方法
add: function() {
// 把部门的字段封装了成一个payload对象
const payload = {
// id:this.id,
name: this.name,
loc: this.loc
};
this.adddept(payload);
// 清除原来的数据
this.name='';
this.loc='';
},
// 编辑部门数据的方法
edit: function(i) {
// 获得编辑项的索引
this.editIndex = i;
this.editItem = {};
this.editItem.id=this.depts[i].id;
this.editItem.name = this.depts[i].name;
this.editItem.loc = this.depts[i].loc;
},
// 更新部门数据的方法
update: function() {
// this.depts.splice(this.editIndex, 1, this.editItem);
console.log( this.editItem);
this.updatedept(this.editItem)
}
},
computed: {
...mapState(["depts"])
},
created() {
this.getdepts();
}
};
</script>
About.vue
// staff
<template>
<div class="row">
<div class="col-lg-4 col-sm-12">
<!-- 表单 -->
<div class="form-group">
<label for>员工的名字:</label>
<input
v-model="name"
type="text"
name
id
class="form-control"
placeholder
aria-describedby="helpId"
/>
</div>
<div class="form-group">
<label for>员工的职位:</label>
<input
v-model="job"
type="text"
name
id
class="form-control"
placeholder
aria-describedby="helpId"
/>
</div>
<div class="form-group">
<label for>员工的电话:</label>
<input
v-model="phone"
type="text"
name
id
class="form-control"
placeholder
aria-describedby="helpId"
/>
</div>
<!-- 创建按钮 -->
<button @click="add()" type="button" name id class="btn btn-primary btn-lg btn-block">创建</button>
</div>
<div class="col-lg-8 col-sm-12">
<!-- 表格 -->
<table class="table">
<thead>
<tr>
<th>编号</th>
<th>名字</th>
<th>职位</th>
<th>电话</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(staff, index) in staffs" :key="index">
<td>{{staff.id}}</td>
<td>{{staff.name}}</td>
<td>{{staff.job}}</td>
<td>{{staff.phone}}</td>
<td>
<div class="row">
<button
@click="edit(index)"
type="button"
name
id
class="btn btn-primary mr-3"
data-toggle="modal"
data-target="#modelId"
>编辑</button>
<!-- 模态框 -->
<!-- Button trigger modal -->
<!-- <button type="button" class="btn btn-primary btn-lg" >
Launch
</button>-->
<!-- Modal -->
<div
class="modal fade"
id="modelId"
tabindex="-1"
role="dialog"
aria-labelledby="modelTitleId"
aria-hidden="true"
>
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">请输入你想要更改的员工信息:</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label for>员工的编号:</label>
<input
v-model="editItem.id"
type="text"
name
id
class="form-control"
placeholder
aria-describedby="helpId"
/>
</div>
<div class="form-group">
<label for>员工的名字:</label>
<input
v-model="editItem.name"
type="text"
name
id
class="form-control"
placeholder
aria-describedby="helpId"
/>
</div>
<div class="form-group">
<label for>员工的职位:</label>
<input
v-model="editItem.job"
type="text"
name
id
class="form-control"
placeholder
aria-describedby="helpId"
/>
</div>
<div class="form-group">
<label for>员工的电话:</label>
<input
v-model="editItem.phone"
type="text"
name
id
class="form-control"
placeholder
aria-describedby="helpId"
/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
<button
@click="update()"
type="button"
class="btn btn-primary"
data-dismiss="modal"
>确定</button>
</div>
</div>
</div>
</div>
<button @click="delstaff(staff.id)" type="button" name id class="btn btn-danger">删除</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script>
import { mapState, mapActions } from "vuex";
export default {
name: "About",
data() {
return {
// 职员的名字
name: "",
// 职员的职位
job: "",
// 职员的电话
phone: "",
// 编辑索引
editIndex: 0,
// 编辑的内容
editItem: {}
};
},
methods: {
...mapActions(["getstaffs", "addstaff", "delstaff", "updatestaff"]),
// 创建新员工的方法
add: function() {
const payload = {
name: this.name,
job: this.job,
phone: this.phone
};
this.addstaff(payload);
// 清除输入框中的数据
this.name = "";
this.job = "";
this.phone = "";
},
// 编辑员工信息的方法
edit: function(i) {
// 获取编辑的索引
this.editIndex = i;
this.editItem = {};
this.editItem.id=this.staffs[i].id;
this.editItem.name = this.staffs[i].name;
this.editItem.job = this.staffs[i].job;
this.editItem.phone = this.staffs[i].phone;
},
// 更新员工信息的方法
update: function() {
this.updatestaff(this.editItem);
}
},
computed: {
...mapState(["staffs"])
},
created() {
this.getstaffs();
}
};
</script>
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
const state = {
// 部门列表
depts: [],
// 职员列表
staffs: []
}
const mutations = {
// 获取部门数据的方法
GETDEPTS(state, depts) {
state.depts = depts;
},
// 创建部门的方法
ADDDEPTS(state, dept) {
state.depts.push(dept)
},
// 获取职工数据的方法
GETSTAFFS(state, staffs) {
state.staffs = staffs;
},
// 创建员工数据的方法
ADDSTAFF(state,staff){
state.staffs.push(staff)
}
}
const actions = {
// 从服务端获取部门数据
getdepts(context) {
const url = 'http://121.41.98.23:9000/api/v1/dept';
axios.get(url)
.then(res => {
console.log(res);
context.commit('GETDEPTS', res.data);
})
.catch(err => {
console.error(err);
})
},
// 向服务端增加部门数据
adddept(context, payload) {
const url = 'http://121.41.98.23:9000/api/v1/dept';
axios.post(url, payload)
.then(res => {
console.log(res)
context.commit('ADDDEPTS', res.data);
// 再次从服务端获取新的数据
axios.get(url)
.then(res => {
console.log(res)
context.commit('GETDEPTS', res.data)
})
.catch(err => {
console.error(err);
})
})
.catch(err => {
console.error(err);
})
},
// 删除服务端的部门数据
deletedept(context, id) {
const url = `http://121.41.98.23:9000/api/v1/dept/${id}`
axios.delete(url)
.then(res => {
console.log(res)
// 删除后再次从服务端获取部门数据
axios.get('http://121.41.98.23:9000/api/v1/dept')
.then(res => {
console.log(res)
context.commit('GETDEPTS', res.data)
})
.catch(err => {
console.error(err);
})
})
.catch(err => {
console.error(err);
})
},
// 更新服务端的部门数据
updatedept(context,payload){
const url = `http://121.41.98.23:9000/api/v1/dept/${payload.id}`
axios.put(url,payload)
.then(res => {
console.log(res)
// 更新后从服务端获取数据
axios.get('http://121.41.98.23:9000/api/v1/dept')
.then(res => {
console.log(res)
context.commit('GETDEPTS', res.data)
})
.catch(err => {
console.error(err);
})
})
.catch(err => {
console.error(err);
})
},
// 从服务端获取员工数据
getstaffs(context) {
const url = 'http://121.41.98.23:9000/api/v1/staff';
axios.get(url)
.then(res => {
console.log(res)
context.commit('GETSTAFFS', res.data)
})
.catch(err => {
console.error(err);
})
},
// 向服务端新增员工数据
addstaff(context,payload){
const url = 'http://121.41.98.23:9000/api/v1/staff';
axios.post(url,payload)
.then(res => {
console.log(res)
context.commit('ADDSTAFF',res.data)
//再次获取服务端的员工数据
axios.get('http://121.41.98.23:9000/api/v1/staff')
.then(res => {
console.log(res)
context.commit('GETSTAFFS', res.data)
})
.catch(err => {
console.error(err);
})
})
.catch(err => {
console.error(err);
})
},
// 删除服务端的员工数据
delstaff(context,id){
const url = `http://121.41.98.23:9000/api/v1/staff/${id}`
axios.delete(url)
.then(res => {
console.log(res)
// 再次获取员工数据
axios.get('http://121.41.98.23:9000/api/v1/staff')
.then(res => {
console.log(res)
context.commit('GETSTAFFS', res.data)
})
.catch(err => {
console.error(err);
})
})
.catch(err => {
console.error(err);
})
},
// 修改服务端的员工数据
updatestaff(context,payload){
const url = `http://121.41.98.23:9000/api/v1/staff/${payload.id}`
axios.put(url,payload)
.then(res => {
console.log(res)
// 再次获取服务端的员工数据
axios.get('http://121.41.98.23:9000/api/v1/staff')
.then(res => {
console.log(res)
context.commit('GETSTAFFS', res.data)
})
.catch(err => {
console.error(err);
})
})
.catch(err => {
console.error(err);
})
}
}
const getters = {
}
export default new Vuex.Store({
state: state,
mutations: mutations,
actions: actions,
modules: {
},
getters: getters
})
界面效果如图:
关于MySQL以及Postman的使用,感兴趣的小伙伴可以去我的其他博客看,以上实现了前后端分离开发,大大减少了开发的时间。此外,有问题的欢迎留言!!!