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);
}
}
posted @ 2021-04-25 16:35  MrZ-blog  阅读(919)  评论(1编辑  收藏  举报