提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 一、后端springboot代码
- 1.创建一个数据库,并设计一个User表;将生成好的bean实体类,mapper接口,mapper.xml文件放在src对应的包下。
- 代码如下(示例):
- 2.数据库和表结构创建
- 3.在springboot的src/main/java文件下创建包并将bean,mapper,mapper.xml放入对应包中
- 4.考虑到有的小伙伴没有逆向工程,这里把bean,mapper,mapper.xml,和application.yml配置的源码给出
- 5.配置application.yml(springboot有两种配置文件格式application.yml和application.properties,这里用yml格式配置)
- 6.在springboot启动器Application上加上注解@MapperScan
- 7.启动Application
- 二、前端Vue-Element ui代码
- 1.在Vue项目的src/views 下新建一个Test.vue来测试Vue项目
- 2.在src/router 打开index.js 添加Test.vue的路由
- 3.在App.vue中添加`'<router-view> </router-view>'`标签让页面能够跳转
- 4.让vue项目启动后默认访问路径中不要有‘/#/’需要在index.js中修改mode: 'history'
- 5.在idea中打开Terminal窗口输入npm run serve运行Vue项目
- 6.新建Index.vue来实现查询(别忘记配路由)
- 7.新建Insert.vue来实现增加(别忘记配路由)
- 8.新建Update.vue来实现修改(别忘记添加路由)
- 9.在index.vue中对删除按钮完善删除方法
- 总结
前言
提示:本篇仅记录在vue和springboot项目框架完成的情况下:
最近学习了一下springboot+mybatis+vue+element ui的前后分离项目的搭建以及实现其简单的CRUD增删改查。前来记录一下
提示:以下是本篇文章正文内容,下面案例可供参考
一、后端springboot代码
在后台中一般不会手动编写bean实体类,mapper接口,mapper.xml文件;这三个文件是可以通过逆向工程自动生成的,不知道的小伙伴可以学习下逆向工程,此文章带有这3文件源码。
1.创建一个数据库,并设计一个User表;将生成好的bean实体类,mapper接口,mapper.xml文件放在src对应的包下。
代码如下(示例):
2.数据库和表结构创建
SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;
DROP DATABASE IF EXISTS 'webuser';
CREATE DATABASE 'webuser';
USE 'webuser';
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`proinfo` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 12 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'root', 'root', '我是管理员');
INSERT INTO `user` VALUES (3, 'admin', '123', '超级管理员');
INSERT INTO `user` VALUES (6, '测试VUE', '123', '辣鸡管理员');
INSERT INTO `user` VALUES (11, '测试2', '123', '12313');
SET FOREIGN_KEY_CHECKS = 1;
3.在springboot的src/main/java文件下创建包并将bean,mapper,mapper.xml放入对应包中
4.考虑到有的小伙伴没有逆向工程,这里把bean,mapper,mapper.xml,和application.yml配置的源码给出
user.java
package com.wzy.demo.bean;
public class User {
private Integer id;
private String name;
private String password;
private String proinfo;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getProinfo() {
return proinfo;
}
public void setProinfo(String proinfo) {
this.proinfo = proinfo == null ? null : proinfo.trim();
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
", proinfo='" + proinfo + '\'' +
'}';
}
}
userMapper.java(别忘记加@Repository注解了哦)
package com.wzy.demo.mapper;
import com.wzy.demo.bean.User;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
User selectByPrimaryKey(Integer id);
List<User> selectAll();
int updateByPrimaryKey(User record);
List<User> selectByName(String name);
}
userService
package com.wzy.demo.service;
import com.wzy.demo.bean.User;
import java.util.List;
public interface userService {
int deleteByPrimaryKey(Integer id);
int insert(User record);
User selectByPrimaryKey(Integer id);
List<User> selectAll();
int updateByPrimaryKey(User record);
}
userServiceImpl(别忘记加@Service注解哦)
package com.wzy.demo.service.impl;
import com.wzy.demo.bean.User;
import com.wzy.demo.mapper.UserMapper;
import com.wzy.demo.service.userService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class userServiceImpl implements userService {
@Resource
private UserMapper mapper;
@Override
public int deleteByPrimaryKey(Integer id) {
return mapper.deleteByPrimaryKey(id);
}
@Override
public int insert(User record) {
return mapper.insert(record);
}
@Override
public User selectByPrimaryKey(Integer id) {
return mapper.selectByPrimaryKey(id);
}
@Override
public List<User> selectAll() {
return mapper.selectAll();
}
@Override
public int updateByPrimaryKey(User record) {
return mapper.updateByPrimaryKey(record);
}
}
mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.wzy.demo.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="com.wzy.demo.bean.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="proinfo" property="proinfo" jdbcType="VARCHAR" />
</resultMap>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.wzy.demo.bean.User" >
insert into user (id, name, password,
proinfo)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{proinfo,jdbcType=VARCHAR})
</insert>
<update id="updateByPrimaryKey" parameterType="com.wzy.demo.bean.User" >
update user
set name = #{name,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
proinfo = #{proinfo,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select id, name, password, proinfo
from user
where id = #{id,jdbcType=INTEGER}
</select>
<select id="selectAll" resultMap="BaseResultMap" >
select id, name, password, proinfo
from user
</select>
</mapper>
userController(@CrossOrigin为了解决vue访问后台数据出现跨域的问题,@RestController让Controller接收返回json数据)
package com.wzy.demo.controllers;
import com.wzy.demo.bean.User;
import com.wzy.demo.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@CrossOrigin
@RestController
public class userController {
@Autowired
userService service;
@GetMapping("/list")//查询所有user
public List<User> selectAll() {
return service.selectAll();
}
@RequestMapping("/user/{id}")//根据id查询user
public User selectById(@PathVariable int id) {
return service.selectByPrimaryKey(id);
}
@PostMapping("/insert")//新增user
public int addUser(@RequestBody User user){
return service.insert(user);
}
@PutMapping("/update")//修改更新user
public int updateUser(@RequestBody User user){
return service.updateByPrimaryKey(user);
}
@DeleteMapping("/delete/{param}")//根据id删除user
public int deleteUser( @PathVariable int param){
return service.deleteByPrimaryKey(param);
}
}
5.配置application.yml(springboot有两种配置文件格式application.yml和application.properties,这里用yml格式配置)
spring:
datasource:
name: localmysql
driver-class-name: com.mysql.jdbc.Driver #本文使用mysql5的配置,如果是mysql8略有不同
url: jdbc:mysql://localhost:3306/webuser
username:
password:
server:
port: 80
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.wzy.demo.bean #指明mapper.xml中的实体类的包
6.在springboot启动器Application上加上注解@MapperScan
不加注解启动会失败哦
package com.wzy.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.wzy.demo.mapper")//为userMapper.java的包路径
public class VuespringbootdemoApplication {
public static void main(String[] args) {
SpringApplication.run(VuespringbootdemoApplication.class, args);
}
}
7.启动Application
运行结果如下(示例):
浏览器输入http://localhost/list访问数据接口。
数据能被访问那么后台数据接口就算开发完毕了!
二、前端Vue-Element ui代码
1.在Vue项目的src/views 下新建一个Test.vue来测试Vue项目
<template>
<el-row>
<el-button>默认按钮</el-button>
<el-button type="primary">主要按钮</el-button>
<el-button type="success">成功按钮</el-button>
<el-button type="info">信息按钮</el-button>
<el-button type="warning">警告按钮</el-button>
<el-button type="danger">危险按钮</el-button>
</el-row>
</template>
<script>
export default {
name: "Test"
}
</script>
<style scoped>
</style>
tips:每次新建vue文件后记得添加路由
2.在src/router 打开index.js 添加Test.vue的路由
import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import Test from "../views/Test";
import Index from "../views/Index"
import Update from "../views/Update";
import Insert from "../views/Insert"
Vue.use(VueRouter);
const routes = [
{//增加页面
path: '/insert',
name: 'Insert',
component: Insert
},
{//修改也买你
path: '/update',
name: 'Update',
component: Update
},
{//查询页面
path: '/index',
name: 'Index',
component: Index
},
{//测试页面
path: '/test',
name: 'Test',
component: Test
},
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
}
];
const router = new VueRouter({
mode: 'history',
routes
});
export default router
3.在App.vue中添加'<router-view> </router-view>'
标签让页面能够跳转
<template>
<div id="app">
<router-view>
</router-view>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'app',
components: {
HelloWorld
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
4.让vue项目启动后默认访问路径中不要有‘/#/’需要在index.js中修改mode: ‘history’
5.在idea中打开Terminal窗口输入npm run serve运行Vue项目
浏览器输入http://localhost:8080/test查看测试页面
vue项目也没有问题了,可以开始写增删改查功能页面了
6.新建Index.vue来实现查询(别忘记配路由)
<template>
<el-table
:data="tableData"
border
style="width: 700px">
<el-table-column
fixed
prop="id"
label="id"
width="150">
</el-table-column>
<el-table-column
prop="name"
label="用户名"
width="120">
</el-table-column>
<el-table-column
prop="password"
label="密码"
width="120">
</el-table-column>
<el-table-column
prop="proinfo"
label="个人信息"
width="120">
</el-table-column>
<el-table-column label="操作">
<template slot-scope="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>
</template>
<script>
export default {
name: "index",
created() {
let _this = this;
axios.get('http://localhost/list').then(function (resp) {
console.log(resp.data);
_this.tableData = resp.data
})
},
methods: {
handleEdit(row){
this.$router.push('/update?id='+row.id)
},
handleDelete(row) {
let _this = this;
this.$confirm('此操作将永久删除'+row.name+'账号信息, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
axios.delete('http://localhost/delete/'+row.id).then(function (resp) {
if (resp.data>0){
_this.$alert(row.name+'已被删除!', '提示', {
confirmButtonText: '确定',
callback: action => {
location.reload()
}
});
}
})
}).catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
});
});
}
},
data() {
return {
tableData: ''
}
}
}
</script>
<style scoped>
</style>
浏览器输入http://localhost:8080/index访问vue页面
7.新建Insert.vue来实现增加(别忘记配路由)
<template>
<div style="width: 600px">
<el-form ref="form" :rules="rules" :model="form" label-width="80px">
<el-form-item label="name" prop="name">
<el-input v-model="form.name"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input v-model="form.password"></el-input>
</el-form-item>
<el-form-item label="个人信息" prop="proinfo">
<el-input v-model="form.proinfo"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit('form')">提交</el-button>
<el-button>取消</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
name: "Insert",
data(){
return{
form:{
id:'',
name:'',
password:'',
proinfo:''
},
rules: {
name: [
{ required: true, message: '用户名不能为空', trigger: 'blur' },
{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
],
password: [
{ required: true, message: '密码不能为空', trigger: 'blur' },
{ min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
],
proinfo: [
{ required: true, message: '个人信息不能为空', trigger: 'blur' }
]
}
}
},
methods:{
onSubmit(formName){
let _this = this;
this.$refs[formName].validate((valid) => {
if (valid) {
console.log(_this.form);
axios.post('http://localhost/insert/',this.form).then(function (resp) {
if (resp.data>0){
_this.$alert(_this.form.name+'已添加成功!', '提示', {
confirmButtonText: '确定',
callback: action => {
_this.$router.push('/index')
}
});
}
})
}
});
}
}
}
</script>
<style scoped>
</style>
浏览器输入http://localhost:8080/insert访问vue页面
8.新建Update.vue来实现修改(别忘记添加路由)
<template>
<div style="width: 600px">
<el-form ref="form" :rules="rules" :model="form" label-width="80px">
<el-form-item label="id" :rules="[
{required:true, message:'id不能为空'},
{type:'number',message: 'id必须为number'}
]" prop="id">
<el-input v-model.number="form.id" ></el-input>
</el-form-item>
<el-form-item label="name" prop="name">
<el-input v-model="form.name"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input v-model="form.password"></el-input>
</el-form-item>
<el-form-item label="个人信息" prop="proinfo">
<el-input v-model="form.proinfo"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit('form')">提交</el-button>
<el-button>取消</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
name: "Update",
created() {
let _this = this;
axios.get('http://localhost/user/'+this.$route.query.id).then(function (resp) {
_this.form=resp.data
})
},
data(){
return{
form:{
id:'',
name:'',
password:'',
proinfo:''
},
rules: {
name: [
{ required: true, message: '用户名不能为空', trigger: 'blur' },
{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
],
password: [
{ required: true, message: '密码不能为空', trigger: 'blur' },
{ min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
],
proinfo: [
{ required: true, message: '个人信息不能为空', trigger: 'blur' }
]
}
}
},
methods:{
onSubmit(formName){
let _this = this;
this.$refs[formName].validate((valid) => {
if (valid) {
console.log(_this.form);
axios.put('http://localhost/update/',this.form).then(function (resp) {
if (resp.data>0){
_this.$alert(_this.form.name+'已被修改!', '提示', {
confirmButtonText: '确定',
callback: action => {
_this.$router.push('/index')
}
});
}
})
}
});
}
}
}
</script>
<style scoped>
</style>
点击index页面上的编辑按钮跳转到update来实现初始化数据
9.在index.vue中对删除按钮完善删除方法
对删除按钮绑定@click方法
methods: {
handleDelete(row) {
let _this = this;
this.$confirm('此操作将永久删除'+row.name+'账号信息, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
axios.delete('http://localhost/delete/'+row.id).then(function (resp) {
if (resp.data>0){
_this.$alert(row.name+'已被删除!', '提示', {
confirmButtonText: '确定',
callback: action => {
location.reload()
}
});
}
})
}).catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
});
});
}
}
点击删除按钮
总结
以上就是今天要讲的内容,本文仅仅简单介绍了springboot+vue的简单用法,通过这些小demo也能让我们窥一斑而知全豹对springboot+vue这种前后分离的框架更加熟悉。博主也是萌新,正在不断学习进步,博文中若有不对之处,望各位不吝赐教相互学习,共同进步!!