SpringBoot+VUE創建前后端分離項目


1、開發工具:

  后端使用idea,前端使用vscode

2、創建后端項目:

  參考網址:https://www.cnblogs.com/little-rain/p/11063967.html

3、創建前端項目:

  參考網址:https://www.cnblogs.com/jianguo221/p/11487532.html

  需要安裝各種插件,示例:

  配置鏡像:npm config set registry=http://registry.npm.taobao.org

  npm install npm -g        更新npm

  npm install vue -g         安裝vue

  npm install vue-router -g         安裝vue-router

  npm install vue-cli -g               安裝vue腳手架

 

4、打開前端文件后安裝組件Element-ui:

  詳見官網組件:https://element.eleme.cn/#/zh-CN/component/installation

  npm i element-ui -S     引入Element-ui插件

  npm install babel-plugin-component -D      引入組件,減小項目體積(可有可無)

  前端項目啟動命令:npm run dev

5、后端配置文件pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 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">
<modelVersion>4.0.0</modelVersion>

<groupId>com.itmate</groupId>
<artifactId>webpro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>webpro</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<!-- 分頁插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>

<!-- 集成druid,使用連接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>

<!--swagger 文檔注釋-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>

<!--swagger需要的一個依賴組件-->
<!--<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.6</version>
</dependency>-->
<!--swagger-->
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

<!-- mybatis generator 自動生成代碼插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generator.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
</plugins>
</build>
</project>

6、application.yml

#端口配置
server:
port: 8080

#swagger 配置
swagger2:
enable: true

spring:
datasource:
name: webpro
url: jdbc:mysql://localhost:3306/engine_db?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
username: root
password: 123456
# 使用druid數據源
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20

## 該配置節點為獨立的節點,有很多同學容易將這個配置放在spring的節點下,導致配置無法被識別
mybatis:
mapper-locations: classpath:mapper/*.xml #注意:一定要對應mapper映射xml文件的所在路徑
type-aliases-package: com.itmate.webpro.entity # 注意:對應實體類的路徑

#pagehelper分頁插件
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql

7、前端配置文件main.js

// 參考 Element-ui 。
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui'
import axios from 'axios'
import 'element-ui/lib/theme-chalk/index.css';

import store from './store.js'
import './common/directives.js'
import '@/assets/iconfont.css'
import '@/assets/css/style.css'

Vue.config.productionTip = false
Vue.use(ElementUI)
Vue.prototype.$axios = axios

Vue.component('footer-copyright', {
  template: '<p class="footer-msg">*******項目*********<a href="http://www.miibeian.gov.cn" target="_blank">******編號******</a></p>'
});

Vue.filter('formatDateTime', function (value) {
  if (!value) return ''
  let date = new Date(value);
  let y = date.getFullYear() + '/';
  let mon = (date.getMonth() + 1) + '/';
  let d = date.getDate();
  return y + mon + d;
});

new Vue({
  router,
  store,
  el: '#app',
  render: h => h(App)
})
8、配置路由router/index.js(用於跳轉頁面的):
// 頁面簡稱
import Vue from 'vue'
import Router from 'vue-router'
import NotFound from '@/components/404.vue'
import Register from '@/views/admin/register.vue'

// 懶加載方式,當路由被訪問的時候才加載對應組件
const Login = resolve => require(['@/views/login'], resolve)

Vue.use(Router)

let router = new Router({
  routes: [
    {
      path: '/login',
      type: 'login',
      component: Login
    },
    {
      path: '/register',
      type: 'register',
      component: Register
    },
    {
      path: '*',
      component: NotFound
    }
  ]
});

router.beforeEach((to, from, next) => {
  // console.log('to:' + to.path)
  if (to.path.startsWith('/login')) {
    window.localStorage.removeItem('access-user')
    next()
  } else if(to.path.startsWith('/register')){
    window.localStorage.removeItem('access-user')
    next()
  } else {
    let user = JSON.parse(window.localStorage.getItem('access-user'))
    if (!user) {
      next({path: '/login'})
    } else {
      next()
    }
  }
});

export default router
9、配置前端跳轉后端方法的API(api/index.js):
  
import * as API from './'

export default {
  //查詢企業信息
  findEnterPrise: params => {
    return API.POST('/enterprise/findEnterPrise', params)
  },
  //新增企業信息
  saveEnterPrise: params => {
    return API.POST('/enterprise/saveEnterPrise', params)
  }
}

 

10、前端方法示例: 

<script>
import API from '../../api/index.js'
  export default {
    data(){
      return {
        msg:'',
        form: {
          number: ' ',
          name: ' '
        }
      };
    },
    methods: {
  // 保存按鈕
      save(){
        let params = {
          number: this.form.number,
          name: this.form.name
        };
  // 此處的API為引入上述 import 的地址,即(9)中的 api/index.js 。
        API.saveEnterPrise(params).then(res =>{
   // 返回值 code=0 ,為成功,則跳轉另一頁面。
          if(res.code === 0) {
            this.$router.push({path:'./list'});
          } else {
            this.$message.error(res.msg);
          }
        });
      }
    }
  }
</script>

12、后端接收前端信息的Controller:

package com.itmate.webpro.controller;

import com.itmate.webpro.common.JsonData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping(value = "/enterprise")
@Api(value = "企業信息" , tags = {"企業信息"})
public class EnterpriseController {

@Autowired
private EnterPriseService enterPriseService;

@ApiOperation(value= "查詢", notes = "查詢")
@RequestMapping(path = "/findEnterPrise", method = RequestMethod.POST)
public JsonData findEnterPrise(@RequestBody EnterPrise enterPrise) {
JsonData jsonData = new JsonData();
String[] array = enterPrise.getArray();
List<EnterPrise> list = enterPriseService.findEnterPrise(enterPrise.getName());

jsonData.setCode(0);
jsonData.setMsg("請求成功");
jsonData.setData(list);
return jsonData;
}

@ApiOperation(value = "保存" , notes = "保存")
@RequestMapping(path = "/saveEnterPrise",method = RequestMethod.POST)
public JsonData saveEnterPrise(@RequestBody EnterPrise enterPrise){
JsonData jsonData = new JsonData();
Boolean flag = enterPriseService.saveEnterPrise(enterPrise);

if(flag){
jsonData.setCode(0);
jsonData.setMsg("添加成功");
jsonData.setData(null);
}else{
jsonData.setCode(-1);
jsonData.setMsg("添加失敗");
jsonData.setData(null);
}
return jsonData;
}
}
12、后端啟動項(WebApplication.java):
package com.itmate.webpro;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
// 配置成Controller
@RestController
// 將項目中對應的mapper類的路徑加進來
@MapperScan("com.itmate.webpro.dao")
@Api(value="默認", tags = {"默認"})
public class WebproApplication {

@ApiOperation(value = "首頁", notes = "首頁")
// 配置默認路徑
@RequestMapping(value = "/first", method = RequestMethod.GET)
public String home(){
return "hello boot";
}

public static void main(String[] args) {
SpringApplication.run(WebproApplication.class, args);
}
}

13、解決前后端鏈接跨域問題(CorsConfig.java):
package com.itmate.webpro.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {

private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 允許任何域名使用
corsConfiguration.addAllowedHeader("*"); // 允許任何頭
corsConfiguration.addAllowedMethod("*"); // 允許任何方法(post、get等)
return corsConfiguration;
}

@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 對接口配置跨域設置
return new CorsFilter(source);
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM