vue后端框架mysql_springboot + vue 前后端结合·数据库查询
springboot + vue 前后端結合·數據庫查詢
數據庫部分:
/*
Navicat Premium Data Transfer
Source Server : localHost
Source Server Type : MySQL
Source Server Version : 50529
Source Host : localhost:3306
Source Schema : vue-demo
Target Server Type : MySQL
Target Server Version : 50529
File Encoding : 65001
Date: 08/07/2020 17:57:30
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`age` int(4) NOT NULL,
`address` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '張飛', 18, '三國');
INSERT INTO `user` VALUES (2, '劉備', 10, '三國');
INSERT INTO `user` VALUES (3, '關羽', 27, '三國');
INSERT INTO `user` VALUES (4, '曹操', 11, '三國');
INSERT INTO `user` VALUES (5, '呂布', 26, '中國 上海 浦東');
INSERT INTO `user` VALUES (6, '杜坡', 23, '北京');
SET FOREIGN_KEY_CHECKS = 1;
后端項目結構:
CORSConfig.java
@Configuration
public class CORSConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
// 限制了路徑和域名的訪問
registry.addMapping("/api*").allowedOrigins("http://localhost:8080");
}
};
}
}
UserController.java
package com.csyd.controller;
import com.csyd.pojo.User;
import com.csyd.pojo.vo.LoginVo;
import com.csyd.pojo.vo.PageVo;
import com.csyd.result.Result;
import com.csyd.result.ResultGenerator;
import com.csyd.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.Objects;
@Controller
@RequestMapping("/api")
public class UserController {
@Autowired
UserService userService;
@CrossOrigin //跨域請求必加
@RequestMapping("/user/login")
@ResponseBody
public Result login(@Valid @RequestBody LoginVo loginVo, BindingResult bindingResult){
if (bindingResult.hasErrors()) {
String message = String.format("登陸失敗,詳細信息[%s]。", bindingResult.getFieldError().getDefaultMessage());
return ResultGenerator.genFailResult(message);
}
if (!Objects.equals("admin", loginVo.getUsername()) || !Objects.equals("123456", loginVo.getPassword())) {
String message = String.format("登陸失敗,詳細信息[用戶名、密碼信息不正確]。");
return ResultGenerator.genFailResult(message);
}
return ResultGenerator.genSuccessResult();
}
@CrossOrigin
@RequestMapping("/user/userList")
@ResponseBody
public Result userList(@RequestBody PageVo pageVo){
PageInfo userPage = userService.userPage(pageVo.getPageNum(), pageVo.getPageSize());
return ResultGenerator.genSuccessResult(userPage);
}
}
mapper.java
package com.csyd.dao;
import com.csyd.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
List selectAll();
}
LoginVo.java
package com.csyd.pojo.vo;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotNull;
public class LoginVo {
@NotNull(message="用戶名不允許為空")
@Length(min=3,max=16,message="用戶名長度不正確!")
private String username;
@NotNull(message="密碼不允許為空")
@Length(min=6,max=16,message="密碼長度不正確!")
private String password;
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
}
PageVo.java
package com.csyd.pojo.vo;
public class PageVo {
private int pageNum;
private int pageSize;
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
}
User.java
package com.csyd.pojo;
import java.io.Serializable;
public class User implements Serializable {
private Integer id;
private String name;
private Integer age;
private String address;
private static final long serialVersionUID = 1L;
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;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Result.java
package com.csyd.result;
/**
* 統一API響應結果封裝
*/
public class Result {
private int code;
private String message;
private Object data;
public Result setCode(ResultCode resultCode) {
this.code = resultCode.getCode();
return this;
}
public int getCode() {
return code;
}
public Result setCode(int code) {
this.code = code;
return this;
}
public String getMessage() {
return message;
}
public Result setMessage(String message) {
this.message = message;
return this;
}
public Object getData() {
return data;
}
public Result setData(Object data) {
this.data = data;
return this;
}
}
ResultCode.java
package com.csyd.result;
/**
* 響應碼枚舉,參考HTTP狀態碼的語義
*/
public enum ResultCode {
SUCCESS(200, "sucess"),//成功
FAIL(400, "失敗"),//失敗
;
private Integer code;
private String msg;
ResultCode(int code) {
this.code = code;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
ResultCode(int code, String msg) {
this.code = code;
this.msg = msg;
}
}
ResultGenerator.java
package com.csyd.result;
/**
* 響應結果生成工具
*/
public class ResultGenerator {
private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS";
public static Result genSuccessResult() {
return new Result()
.setCode(ResultCode.SUCCESS)
.setMessage(DEFAULT_SUCCESS_MESSAGE);
}
public static Result genSuccessResult(Object data) {
return new Result()
.setCode(ResultCode.SUCCESS)
.setMessage(DEFAULT_SUCCESS_MESSAGE)
.setData(data);
}
public static Result genFailResult(String message) {
return new Result()
.setCode(ResultCode.FAIL)
.setMessage(message);
}
public static Result genFailResult(ResultCode resultCode) {
return new Result()
.setCode(resultCode.getCode())
.setMessage(resultCode.getMsg());
}
}
UserService.java
package com.csyd.service;
import com.csyd.dao.UserMapper;
import com.csyd.pojo.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public PageInfo userPage(Integer pageNum, Integer pageSize){
PageHelper.startPage(pageNum, pageSize);
List userList = userMapper.selectAll();
PageInfo userPageInfo = new PageInfo<>(userList);
return userPageInfo;
}
}
package com.csyd;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Vueproject {
public static void main(String[] args) {
SpringApplication.run(Vueproject.class, args);
}
}
application.properties
server.port=8765
#數據庫
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/vue-demo
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#mybatis(注意必不可缺!不然找不到mapper.)
mybatis.mapper-locations=classpath:/mapper/*Mapper.xml
mybatis.type-aliases-package=com.csyd.pojo
generatorConfig.xml
/p>
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/vue-demo"
userId="root"
password="root"/>
domainObjectName="User" enableCountByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
enableUpdateByExample="false">
pom.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.csyd
vueproject
1.0-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
2.0.0.RELEASE
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.6
true
mysql
mysql-connector-java
5.1.45
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
org.springframework.boot
spring-boot-starter-jdbc
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
com.github.pagehelper
pagehelper-spring-boot-starter
1.2.3
PostMan測試一下接口:
搭建前端VUE
目錄結構:
Layout.vue
.layout{
border: 1px solid #d7dde4;
background: #f5f7f9;
position: relative;
border-radius: 4px;
overflow: hidden;
}
.layout-header-bar{
background: #f4b1df;
box-shadow: 0 1px 1px rgba(0,0,0,.1);
}
.layout-logo-left{
width: 90%;
height: 30px;
background: #5b6270;
border-radius: 3px;
margin: 15px auto;
}
.menu-icon{
transition: all .3s;
}
.rotate-icon{
transform: rotate(-90deg);
}
.menu-item span{
display: inline-block;
overflow: hidden;
width: 69px;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: bottom;
transition: width .2s ease .2s;
}
.menu-item i{
transform: translateX(0px);
transition: font-size .2s ease, transform .2s ease;
vertical-align: middle;
font-size: 16px;
}
.menu-item .ivu-menu-item{
color: darkgray;
}
.collapsed-menu span{
width: 0px;
transition: width .2s ease;
}
.collapsed-menu i{
transform: translateX(5px);
transition: font-size .2s ease .2s, transform .2s ease .2s;
vertical-align: middle;
font-size: 22px;
}
.layout-logo{
width: 200px;
height: 50px;
/*background: white;*/
border-radius: 3px;
float: right;
position: relative;
top: 5px;
right: 20px;
text-align: center;
background: url("../../assets/logo.png");
background-size: 200px 50px;
}
退出登錄
Option 1
Option 2
Option 3
export default {
data () {
return {
isCollapsed: false
}
},
computed: {
rotateIcon () {
return [
'menu-icon',
this.isCollapsed ? 'rotate-icon' : ''
];
},
menuitemClasses () {
return [
'menu-item',
this.isCollapsed ? 'collapsed-menu' : ''
]
}
},
methods: {
collapsedSider () {
this.$refs.side1.toggleCollapse();
}
}
}
HelloWorld.vue
{{ msg }}
Essential Links
href="https://vuejs.org"
target="_blank"
>
Core Docs
href="https://forum.vuejs.org"
target="_blank"
>
Forum
href="https://chat.vuejs.org"
target="_blank"
>
Community Chat
href="https://twitter.com/vuejs"
target="_blank"
>
Twitter
href="http://vuejs-templates.github.io/webpack/"
target="_blank"
>
Docs for This Template
Ecosystem
href="http://router.vuejs.org/"
target="_blank"
>
vue-router
href="http://vuex.vuejs.org/"
target="_blank"
>
vuex
href="http://vue-loader.vuejs.org/"
target="_blank"
>
vue-loader
href="https://github.com/vuejs/awesome-vue"
target="_blank"
>
awesome-vue
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
Login.vue
html,body {
width: 100%;
height: 100%;
background: url("../assets/background.jpg");
}
.from-wrap{
width: 100%;
height: 260px;
border-radius: 10px;
background-color: #fff;
padding: 20px 30px;
margin-top: 60%;
}
h1 {
text-align: center;
margin-bottom: 20px;
}
FormItem {
margin-bottom: 30px;
}
.form-footer {
text-align: right;
}
登錄
Submit
export default {
data () {
return {
loginVo: {
username:'',
password:''
},
ruleValidate: {
username: [
{ required: true, message: '賬號不能為空', trigger: 'blur' },
{ min: 3, max: 16, message: '賬號長度3-16個字符', trigger: 'blur' }
],
password: [
{ required: true, message: '密碼不能為空', trigger: 'blur' },
{ type: 'string', min: 6, max: 16, message: '密碼長度6-16個字符', trigger: 'blur' }
]
},
responseResult: []
}
},
methods: {
handleSubmit () {
this.$axios
.post('/user/login', {
username: this.loginVo.username,
password: this.loginVo.password
})
.then(successResponse => {
this.responseResult = JSON.stringify(successResponse.data);
if (successResponse.data.code === 200) {
this.$router.replace({path: '/manage/page1'})
}else {
alert(successResponse.data.message)
}
})
.catch(function (error) {
console.log(error);
});
}
}
}
Page1.vue
用戶管理
添加
:total="total" :page-size="pageSize" :page-size-opts="pageSizeOpts"
show-total show-sizer
@on-change="changePage" @on-page-size-change="changeSize"/>
export default {
data () {
return {
columns7: [ //這里是table的頭設置
{
title: '名字',
key: 'name',
render: (h, params) => {
return h('div', [
h('Icon', {
props: {
type: 'person'
}
}),
h('strong', params.row.name)
]);
}
},
{
title: '年齡',
key: 'age'
},
{
title: '地址',
key: 'address'
},
{
title: '操作',
key: 'action',
align: 'center',
render: (h, params) => {
return h('div', [
h('Button', {
props: {
type: 'default',
size: 'small',
},
style: {
marginRight: '5px',
},
on: {
click: () => {
this.show(params.index)
}
}
}, '查看'),
h('Button', {
props: {
type: 'primary',
size: 'small'
},
style: {
marginRight: '5px'
},
on: {
// click: () => {
// this.show(params.index)
// }
}
}, '編輯'),
h('Button', {
props: {
type: 'error',
size: 'small'
},
style: {
marginRight: '5px'
},
on: {
// click: () => {
// this.remove(params.index)
// }
}
}, '刪除')
]);
}
}
],
data6: [], //用于接收table的數據
pageSize : 5,
pageNum : 1,
total : undefined,
pageSizeOpts : [5, 10]
}
},
methods: {
getUserList(){
//請求出去的是json
this.$axios
.post('/user/userList', {
pageNum : this.pageNum,
pageSize : this.pageSize
})
.then(successResponse => {
this.responseResult = JSON.stringify(successResponse.data);
if (successResponse.data.code === 200) {
this.data6 = successResponse.data.data.list;
this.total = successResponse.data.data.total;
}else {
alert('系統錯誤');
}
})
.catch(function (error) {
console.log(error);
});
},
changePage(page){
this.pageNum = page;
this.getUserList();
},
changeSize(pageSize){
this.pageSize = pageSize;
this.getUserList();
}
},
created: function () {
this.getUserList();
}
}
index.js
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Login from '@/components/Login'
import Layout from '@/components/common/Layout'
import Page1 from '@/components/Page1'
import Page2 from '@/components/Page2'
import Page3 from '@/components/Page3'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'login',
component: Login
},
{
path: '/hello',
component: HelloWorld
},
{
path: '/manage',
component: Layout,
children: [
{
path: '/manage/page1',
name: 'page1',
component: Page1
},
{
path: '/manage/page2',
name: 'page2',
component: Page2
},
{
path: '/manage/page3',
name: 'page3',
component: Page3
}
]
}
]
})
main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import iView from 'iview' //引入iview
import 'iview/dist/styles/iview.css' //使用iview css
import './theme/index.less';
import './css/common.css'
// 引用axios,并設置基礎URL為后端服務api地址
var axios = require('axios')
//設置默認請求路徑
axios.defaults.baseURL = 'http://localhost:8765/api'
// 將API方法綁定到全局
Vue.prototype.$axios = axios
Vue.use(iView, {
transfer: true,
size: 'large'
});
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: ''
})
Vue啟動
執行:?npm install --save axios
訪問:http://localhost:8080
userName:admin
passWord:123456
這樣我們就實現了springboot + vue 前后端結合·數據庫查詢,部分功能未實現-----------------
總結
以上是生活随笔為你收集整理的vue后端框架mysql_springboot + vue 前后端结合·数据库查询的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: timestamp mysql php_
- 下一篇: j - 数据结构实验:哈希表_一看就懂的