SpringBoot和Vue前后端交流整体过程

SpringBoot和Vue前后端交流整体过程

SpringBoot后端过程

后端的整个操作流程是完成后端数据的传输,整体框架为springboot+mysql+mybatis

springboot设置

   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
     </dependency>
     <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>RELEASE</version>
            <scope>test</scope>
     </dependency>

mysql设置

    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
     </dependency>      
#MYSQL链接
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/company?serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
CREATE TABLE `user` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `username` varchar(25) DEFAULT NULL,
  `password` varchar(25) DEFAULT NULL,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=gb2312

insert into user(id,username,password) values (1,'admin','123')

mybatis设置

  <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
  </dependency>
#添加mybatis配置
mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

lombok设置

    <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
    </dependency>

swagger3.0设置

 <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
 </dependency>

Entity设置

user实体类
@Data
@ApiModel(value = "用户类")
public class User {
    @ApiModelProperty(value = "用户名")
    private String username;
    @ApiModelProperty(value = "用户密码")
    private String password;
}
Result实体类
@Data
@ApiModel(value = "结果返回类")
public class Result<T> {
    @ApiModelProperty(value = "状态码")
    private Integer code;
    @ApiModelProperty(value = "提示消息")
    private String msg;
    @ApiModelProperty(value = "数据")
    private T data;
    /**
     * 构造函数
     * @param code
     * @param msg
     * @param data
     */
    public Result(Integer code,String msg,T data){
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
    public Result(){
    }
ResultEnum枚举类
public enum  ResultEnum {
    /**
     * 成功
     */
    SUCCESS(200),
    /**
     * 失败
     */
    FAIL(400),
    /**
     * 接口不存在
     */
    NOT_FOUND(404),
    /**
     * 服务器内部错误
     */
    INTERNAL_SERVER_ERROR(500);
    public Integer code;
    ResultEnum(Integer code) {
        this.code = code;
    }
}

Util设置

ResultUtil配置类
public class ResultUtil {
    public static <T> Result<T>  defineSuccess(Integer code, T data) {
        Result result = new Result<>();
        result.setCode(code);
        result.setData(data);
        return result;
    }

    public static <T> Result<T> success(T data) {
        Result result = new Result();
        result.setCode(ResultEnum.SUCCESS.code);
        result.setData(data);
        return result;
    }

    public static <T> Result<T> successWithMsg(String msg,T data) {
        Result result = new Result();
        result.setCode(ResultEnum.SUCCESS.code);
        result.setMsg(msg);
        result.setData(data);
        return result;
    }

    public static <T> Result<T> fail(String msg) {
        Result result = new Result();
        result.setCode(ResultEnum.FAIL.code);
        result.setMsg(msg);
        return result;
    }

    public static <T> Result<T> defineFail(int code, String msg){
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }

    public static <T> Result<T> define(int code, String msg, T data){
        Result result = new Result();
        result.setMsg(msg);
        result.setData(data);
        return result;
    }
}

Service设置

public interface UserService {
    /**
     * 查询用户信息
     * @param username
     * @param password
     * @return
     */
    User getUserInfo(String username,String password);
}

ServiceImpl设置

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public User getUserInfo(String username, String password) {
        return userMapper.selectUserInfo(username,password);
    }
}

Mapper设置

@Mapper
@Repository
public interface UserMapper {
    /**
     * 查询用户mapper
     * @param username
     * @param password
     * @return
     */
    User selectUserInfo(@Param("username") String username, @Param("password") String password);
}

mybatis/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="demo.mapper.UserMapper">
    <select id="selectUserInfo" resultType="demo.entity.User">
            select u.username,u.password
            from user u
            where u.username=#{username} and u.password = #{password}
    </select>
</mapper>

Controller设置

@Api(value = "用户控制",tags = {"用户操作接口"})
@RestController
@RequestMapping(value = "/api",produces = "application/json")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    @ApiOperation(value = "查询用户信息")
    public Result getUserInfo(@RequestParam(value = "username")String username,
                              @RequestParam(value = "password")String password) {
        User user = userService.getUserInfo(username, password);
        if (user == null) {
            return ResultUtil.fail("数据库没有这个人");
        } else {
            log.info(user.getUsername()+"========="+user.getPassword()+"==========");
            log.info("hello world");
            return ResultUtil.successWithMsg("success", user);
        }
    }
}

Vue前端过程

vue前端主要是前端页面的编写,接收来自后端的数据和向后端传输数据

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'

Vue.config.productionTip = false

//引入axios
import axios from 'axios'
Vue.prototype.axios = axios

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import login from '@/components/login'
import home from '@/components/home'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: login
    },
    {
      path: '/home',
      name: 'home',
      component: home,
    }   
  ]
})
export default router;

components/login.vue

<template>
  <div>
    <input type="text" v-model="loginForm.username" placeholder="用户名"/>
    <input type="text" v-model="loginForm.password" placeholder="密码"/>
    <button @click="login">登录</button>
  </div>
</template>
 
<script>
import { mapMutations } from 'vuex';
export default {
  data () {
    return {
      loginForm: {
        username: 'admin',
        password: '123'
      }
    }
  }, 
  methods: {
    login () {
        this.axios({
          method:'post',
          url:'/api/login',
          params:{
            username:this.loginForm.username,
            password:this.loginForm.password
          }
        }).then((result) => {
          console.log(result.data)
          // const userinfo = {account:this.loginForm.username,password:this.loginForm.password}
          const userinfo = {account:result.data.data.username,password:result.data.data.password}
          //将数据存储到session中,在其他的页面可以直接取出来使用
          sessionStorage.setItem('userinfo',JSON.stringify(userinfo))
          this.$router.push('/home')          
        }).catch((err) => {
          console.log(err)
        })    
    }
  }
}
</script>

components/home.vue

<template>
    <div>
        <h1>{{userinfo.account}}</h1>
        <h1>{{userinfo.password}}</h1>
    </div>
</template>
<script>
export default {   
    data(){
        return {userinfo: JSON.parse(sessionStorage.getItem('userinfo'))}
    }
}
</script>

config/index.js

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api':{
        target:'http://127.0.0.1:8081',
        changeOrigin: true,
        secure: false
      }
    },

    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

    
    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',

    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,

    cssSourceMap: true
  },

  build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',

    /**
     * Source Maps
     */

    productionSourceMap: true,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',

    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],

    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  }
}
  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值