Copyright (C) 2007 China Mobile Communications Group — Shandong Co., LTD. — Yantai Branch — Marketing Department — Business Support Center

If you want to reprint or use please contact wechat: Mickeywang1998, this project is with the help of online open source code secondary development, this project and its documentation is a single source paid open source project, please respect the author’s creation!

Project Demo

Why do this tutorial?

Before you see: explain in advance, the tutorial is very simple, is the introductory tutorial, do not like spray, go out right turn, the troll as the situation delete comments of ao!

Himself a graduate, undergraduate computer science, in a certain state, hope you can use what they have learned in the enterprise after graduation to cast some, but the technology, all this tutorial is for beginners, is also to myself, good mind not written, hope this tutorial can help to more people like me.

A very simple project, in fact, simple and simple, said difficult also difficult, for beginners, I believe we stepped on many pits, but also around many detours.

Most of the projects based on VUE and Springboot on the Internet are very mature projects, specific mature to what extent it can be said that the project and the framework of the large volume, can be so large that beginners can not see the logic of each other, framework API documents can not understand, how to do, project git down to find their own change it. I found it impossible to change.

The login project is certainly very simple, but for those of you who are new to front-end separation development or who want to move into computing, there is an urgent need for a very basic tutorial on the logic and essentials of the front-end framework, and I did this tutorial with that in mind.

The interface display

Local Environment Construction

Front-end: NodeJS installation

Nodejs is JavaScript running on the server side, and the faster your JS is, the faster our front-end user interaction and submission will be for our login project.

Students who have learned Html5+CSS+JavaScript this set of basic front-end development process should know

This way, with NodeJS, our Vue project works fine. Here are the nodeJS installation steps:

Nodejs installation procedure

  1. Node.js installation package and source code: download node.js

  2. Win10 64bit system user click to download Windows Installer (.msi)64-bit

  1. To install, remember the installation directory of the image below, in case the environment variable PATH does not have nodejs, we also need to look for the directory in the file manager

  1. After the installation is complete, win+R will run CMD, as shown below:
Microsoft Windows [Version10.018363.1316.]
(c) 2019Microsoft Corporation. All rights reserved. C:\Users\w1248>path PATH=F:\Programs\Python\Python38\Scripts\; F:\Programs\Python\Python38\; C:\Program Files (x86)\Common Files\Oracle\Java\javapath; C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9. 0\bin; C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v9. 0\libnvvp; C:\Windows\System32; C:\Windows; C:\Windows\System32\Wbem; C:\Windows\System32\WindowsPowerShell\v1. 0\; C:\Windows\System32\OpenSSH\; C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common; C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR; D:\Program Files\Polyspace\R2019b\runtime\win64; D:\Program Files\Polyspace\R2019b\bin; D:\Program Files\Polyspace\R2019b\polyspace\bin; F:\Program Files\IBM\SPSS\Statistics\25\JRE\bin; D:\Program Files\nodejs\; C:\ProgramData\chocolatey\bin; D:\mysql\mysql-8.021.-winx64\bin; E:\Maven\apache-maven-3.63.\bin; F:\Program Files\Git\cmd; F:\texlive\2020\bin\win32; C:\Users\w1248\AppData\Local\Microsoft\WindowsApps; F:\Program Files\Microsoft VS Code\bin; F:\Program Files\JetBrains\PyCharm Community Edition2020.14.\bin; F:\Program Files\JetBrains\PyCharm2020.14.\bin; C:\Users\w1248\AppData\Local\GitHubDesktop\bin; C:\Users\w1248\AppData\Roaming\npm; D:\Program Files\JetBrains\WebStorm2020.23.\bin;
Copy the code

Insert: PATH has no NodeJS look here!! The environment variable

Nodejs PATH not found under CMD PATH look here!

First, win10 environment below, right click “this computer”, click “properties”

Next, click “Advanced System Settings” and then click “Environment Variables”.

Finally, we need to create a new variable NODE_PATH in the second system variable column, copy the installation path /bin, save all the way.

Ok, moving on, here’s step 5:

  1. Then check the nodeJS version. How to check the nodeJS version using CMD command line? Enter in CMD as follows:
node -v
Copy the code

or

node --version
Copy the code

The installed version is V14.12.0

Front end: NPM installation

The role of NPM

NPM is a package manager under NodeJS, which is installed as soon as nodeJS is installed, though it may not be the latest version. As the name implies, without the package manager, you can’t do any subsequent work.

NPM can solve many problems in NodeJS code deployment. Common usage scenarios are as follows:

  1. Allows users to download third-party packages written by others from the NPM server for local use.

  2. Allows users to download and install command line programs written by others from the NPM server for local use.

  3. Allows users to upload their own packages or command-line programs to the NPM server for others to use.

View the NPM version

NPM is automatically installed after nodeJS is installed. How to use CMD command line to check the version of NPM?

npm -v
Copy the code

Global and local installation of NPM

  1. Global installation

Here is the global installation. You can see the files with the CMD suffix in the root directory. From these files, we can use them directly on the command line. Using XXX –version, etc., is valid regardless of which directory file you are running in.

In other words, global installation means that in any corner of the computer, in any directory, you can use CMD, etc., to find installed components

  1. Local installation

This is not the case with partial installations, which are usually installed in a project and then loaded under the./node_nodules directory. This limitation is that it can only be used in this project.

In particular, tools like WebPack and Babel can be used in a variety of situations and projects.

Upgrade NPM/use Taobao image upgrade

  1. If you want to upgrade, type in CMD
npm install npm -g
Copy the code
  1. Configure Taobao mirror source, and then use the resources of Taobao mirror source to upgrade NPM as follows:

First, modify the mirror site configuration for NPM

npm install -g cnpm --registry=https://registry.npm.taobao.org
Copy the code

Second, check our NPM

C:\Users\w1248>npm config get registry
https://registry.npm.taobao.org/
Copy the code

Finally, update NPM through Taobao mirror source

C:\Users\w1248>npm install npm -g
Copy the code

The screen displays the following:

C:\Users\w1248\AppData\Roaming\npm\npm -> C:\Users\w1248\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js
C:\Users\w1248\AppData\Roaming\npm\npx -> C:\Users\w1248\AppData\Roaming\npm\node_modules\npm\bin\npx-cli.js
+ npm@6.1411.
added 435 packages from 889 contributors in 10.398s
Copy the code

Optional: CNPM installation

Actually, after installing NPM, we can use the NPM package manager to complete the INSTALLATION of CNPM

  1. NPM install -g CNPM install -g CNPM
npm install -g cnpm --registry=https://registry.npm.taobao.org
Copy the code
  1. To check the version of CNPM, enter
cnpm -v
Copy the code

My computer does not have the node_modules directory configured with nodejs. If you did, your node_modules directory would be different.

cnpm@6.11. (C:\Users\w1248\AppData\Roaming\npm\node_modules\cnpm\lib\parse_argv.js)
npm@6.148. (C:\Users\w1248\AppData\Roaming\npm\node_modules\cnpm\node_modules\npm\lib\npm.js)
node@14.12. 0 (D:\Program Files\nodejs\node.exe)
npminstall@3.27. 0 (C:\Users\w1248\AppData\Roaming\npm\node_modules\cnpm\node_modules\npminstall\lib\index.js)
prefix=C:\Users\w1248\AppData\Roaming\npm
win32 x64 10.018363.
registry=https://r.npm.taobao.org
Copy the code

Vue installation

Vue. Js installed

We have installed nodejs and NPM earlier, to install vue.js, enter CMD

npm install vue -g
Copy the code

Vue – the router installation

We have installed nodeJS and NPM. To install vue-Router, enter CMD

npm install vue-router -g
Copy the code

Vue-cli 3 Scaffolding Installation (built-in Webpack)

Now to install the vuE-CLI development scaffolding, enter CMD

npm install vue-cli -g
Copy the code

Using CMD command line, enter the following command to view the vUE version

vue -V
Copy the code

Environment Variable Configuration

Above the nodeJS configuration, we have addressed the configuration of environment variables

Vue front-end page development

IDE used for front-end development: Visual Studio Code

Front-end project Directory:

Vue project initial build (appendix: VSCode plus right-click menu)

Create a VUE project

  1. Create Vue project (go to the folder you want to create, I put it in D:\teaching), create statement is Vue create VUe-spring-loginwork, arrow key up and down you can choose the creation method, I chose default Vue 2 (because I’m not familiar with some syntax changes in Vue 3, I didn’t choose 3)
vue create vue-spring-loginwork
Copy the code

After creation, it looks like this

  1. Go to the created Vue project directory and add the dependency framework in CMD as follows:
cd vue-spring-loginwork
vue add element
npm install axios
npm install vuex --save
npm install vue-router
Copy the code

(1) Go to CD vue-spring-loginwork

(2) Add the Element-UI component developed by ele. me team. We will use some el-form and other styles in VUE (it will be slow to wait for a while).

Fully import, y, zh-cn

Complete the screenshot:

(3) Install AXIOS for network requests

(4) Vuex is installed to manage the state of the front end

(5) Install vUE frame routing to realize the jump of VUE page

(6) Now that the basic framework is done, let’s do a little test

Open the project and our directory looks like this, as shown

At this point we open the terminal below VSCode and type NPM run serve to test:

Enter http://localhost:8080/ to discover the page. (This page indicates that our Element and vue are already installed.)

Add VSCODE to the right-click menu so we can easily open the project!

PS: here, how to add VSCode to our right-click menu so that we can open the project

First, create a aaa. TXT file for your desktop and copy the following code into it

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\*\shell\VSCode]
@="Open with Code"
"Icon"="D:\\Program Files\\Microsoft VS Code\\Code.exe"

[HKEY_CLASSES_ROOT\*\shell\VSCode\command]
@="\"D:\\Program Files\\Microsoft VS Code\\Code.exe\" \"%1\""

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\shell\VSCode]
@="Open with Code"
"Icon"="D:\\Program Files\\Microsoft VS Code\\Code.exe"

[HKEY_CLASSES_ROOT\Directory\shell\VSCode\command]
@="\"D:\\Program Files\\Microsoft VS Code\\Code.exe\" \"%V\""

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\Background\shell\VSCode]
@="Open with Code"
"Icon"="D:\\Program Files\\Microsoft VS Code\\Code.exe"

[HKEY_CLASSES_ROOT\Directory\Background\shell\VSCode\command]
@="\"D:\\Program Files\\Microsoft VS Code\\Code.exe\" \"%V\""

Copy the code

Second, change all of the paths inside to your code.exe path, check your own VSCODE installation path, My code. exe path is “D: Program Files Microsoft VS Code code. exe”. Change D:\Program Files to D:\Program Files, otherwise it will fail)

Finally, TXT named aaA.reg, execute the file, complete!

Modify index.html, app.vue and main.js

Initial front-end Vue project display logic

After the project is established, the page display logic is as follows:

  1. When the browser accesses the project, the index.html file is the first to be accessed
  2. There is a mount point with the ID app, to which our Vue root instance will then be mounted

  1. As the entry file of the vue project, main.js creates a new vue instance in main.js. In the vue instance, the following figure tells the instance where to mount

  1. So the Vue instance is the content of the component app. Vue.

The result: in the Title section of the page, the Title defined in index.html is loaded, and in the body part, the part defined in app.vue is loaded. (Note, however, that the text defined in index. HTML is displayed in the browser immediately after the browser opens.)

To do this, we need to add several folder directories to the project’s SRC directory

  1. API (Network Request Interface)
  2. Router configuration
  3. Store (Vuex Status Management)
  4. Utils (Toolkit for the project)
  5. Views (View package, store page code, can be subcontracted according to the function module)

As shown in the figure:

Let’s modify the basic entries app.vue and main.js

Modified index. HTML

  1. Public directory index. HTML
<! DOCTYPEhtml>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <! -- <title><%= htmlWebpackPlugin.options.title %></title> -->
    <title>Front and rear end separation project demo</title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <! -- built files will be auto injected -->
  </body>
</html>
Copy the code

Modify the App. Vue

  1. App.vue
<template>
  <div>This page is the initial routing page<! -- Route entry and exit, route content will be displayed here -->
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

<style lang="stylus">

</style>
Copy the code

Modify the main js

  1. main.js
import Vue from 'vue'
import App from './App.vue'
import './plugins/element.js'
import router from './router'
import store from './store'


Vue.config.productionTip = false


new Vue({
  render: h= > h(App),Render app. vue via this instance of new
  router,
  store
}).$mount('#app')  // Mount the instance to the location in index.html where the id is app
Copy the code

Prepare vUE interface of Error, login and Success

After modifying the basic entry control of the project, we began to write the login page components, as well as the feedback page components error and success after login

login.vue

<template>
  <div>
    <el-card class="login-form-layout">
      <el-form
        autocomplete="on"
        :model="loginForm"
        ref="loginForm"
        label-position="left"
      >
        <div style="text-align: center">
          <svg-icon icon-class="login-mall" style="width: 56px; height: 56px; color: #409EFF"></svg-icon>
        </div>
        <h2 class="login-title color-main">Element - login UI</h2>
        <el-form-item prop="username">
          <el-input
            name="username"
            type="text"
            v-model="loginForm.username"
            autocomplete="on"
            placeholder="Please enter user name"
          >
            <span slot="prefix">
              <svg-icon icon-class="user" class="color-main"></svg-icon>
            </span>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            name="password"
            :type="pwdType"
            @keyup.enter.native="handleLogin"
            v-model="loginForm.password"
            autocomplete="on"
            placeholder="Please enter your password"
          >
            <span slot="prefix">
              <svg-icon icon-class="password" class="color-main"></svg-icon>
            </span>
            <span slot="suffix" @click="showPwd">
              <svg-icon icon-class="eye" class="color-main"></svg-icon>
            </span>
          </el-input>
        </el-form-item>
        <el-form-item style="margin-bottom: 60px">
          <el-button
            style="width: 100%"
            type="primary"
            :loading="loading"
            @click.native.prevent="handleLogin"
          >The login</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
 
<script>
export default {
  name: "login".data() {
    return {
      loginForm: {
        username: "juejin".password: "123456"
      },
      loading: false.pwdType: "password"}; },methods: {
    showPwd() {
      if (this.pwdType === "password") {
        this.pwdType = "";
      } else {
        this.pwdType = "password"; }},handleLogin() {
      this.$refs.loginForm.validate(valid= > {
        if (valid) {
          this.loading = true;
          // Call the Login method under store
          this.$store
            .dispatch("Login".this.loginForm)// Read username and password in loginForm
            .then(response= > {// Declare a response variable of type JSON
              this.loading = false;
              let code = response.data.code;// Data, code, message is passed from the back end to the front end to code
              if (code == 200) {
                this.$router.push({
                  path: "/success".query: { data: response.data.data }
                });
              } //this.$router.push pushes the information in query to /success based on the route
              else {
                this.$router.push({
                  path: "/error".query: { message: response.data.message }
                });
              }//this.$router.push pushes the information in query to /error based on the route
            })
            .catch(() = > {
              this.loading = false;
            });
        } else {
          // eslint-disable-next-line no-console
          console.log("Invalid parameter validation!");
          return false; }}); }}};</script>
 
<style scoped>
.login-form-layout {
  position: absolute;
  left: 0;
  right: 0;
  width: 360px;
  margin: 140px auto;
  border-top: 10px solid #409eff;
}
 
.login-title {
  text-align: center;
}
 
.login-center-layout {
  background: #409eff;
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
  margin-top: 200px;
}
</style>
Copy the code

success.vue

<template>
    <div>
        <h1>{{MSG}}</h1>
    </div>
</template>

<script>
export default {
    data(){
        return{
            msg:this.$route.query.data//login.vue; //login.vue}; }}</script>

<style>

</style>
Copy the code

error.vue

<template>
    <div>
        <h1>Error: {{MSG}}</h1>
    </div>
</template>

<script>
export default {
    data(){
        return{
            msg:null
        };
    },
    created(){
        this.msg=this.$route.query.message;// Login. vue sends the message from the query route}}</script>

<style>

</style>
Copy the code

Example Register a vue-router route

In this step, we need to configure our router/index.js to configure the page component in our views

The router/index. Js code

import Vue from 'vue' / / into the Vue
import VueRouter from 'vue-router' // Import Vue routes

Vue.use(VueRouter); // Install the plug-in

export const constantRouterMap = [
    // Set the default path. By default, the login page is displayed according to the router-view of app.vue
    { path: '/'.component: () = > import('@/views/login')},

    // Configure the login success page. You need to use the path to jump to the page
    { path: '/success'.component: () = > import('@/views/success')},

    // Configure the login failure page. You need to use the path to switch to the page
    { path: '/error'.component: () = > import('@/views/error'), hidden: true}]export default new VueRouter({
    // mode: 'history', // backend support can be turned on
    scrollBehavior: () = > ({ y: 0 }),
    routes: constantRouterMap // Specify the route list
})
Copy the code

The contents of this (that is, data)

Use Postman for back-end — front-end testing

The data returned from the discovery is as follows

{
    "code": 200."message": "Operation successful"."data": "I'm the success returned by the back end controller @responseBody via the CommonResult API."
}
Copy the code

So that’s already the code

Use Vuex + Axios to make network requests (see the back end first in this chapter)

This is where the front-end project is going to focus, and I’m going to focus on how they interact with the front and back ends.

In fact, THIS tutorial I write the reverse, normal is to write the back end, to write the front end, because the front end he can not write overhead, he needs the back end and the database to do communication.

Important: front-end and back-end pass value fields

Our JSON contains two fields, namely:

{
    "username": "juejin"."password": "123456"
}
Copy the code

Front end is by visiting the page, the POST to the http://localhost:8088/admin/login username and password.

This can be seen in SRC/API /login.js.

After? What is the feedback from the back end?

  1. If successful, this returns:
{
    "code": 200."message": "Operation successful"."data": "I'm the success returned by the back end controller @responseBody via the CommonResult API."
}
Copy the code
  1. On failure, return:
{
    "code": 404."message": "I'm an error returned by the back end controller @responseBody via the CommonResult API."."data": null
}
Copy the code

You’ll notice that success messages are placed in data, whereas failure messages are placed in Message.

This is due to the CommomResult call in the controller at the back end:

In the SRC/main/Java/cn. Eli. Vue. The inside of the API CommonResult method writes:

Take a closer look at the order, and the type of pass:

  1. If successful:

The method is to read a generic data and return code, message (both of which are written in the enumeration), and a generic data.

  1. In case of failure:

The method reads a string of message, returns code, the message that was just read in, and a generic data (which has been set to null).

Let’s see how this enumeration works:


    SUCCESS(200."Operation successful"),
   	FAILED(500."Operation failed"),
    VALIDATE_FAILED(404."Parameter verification failed"),
    UNAUTHORIZED(401."Not logged in or token has expired"),
    FORBIDDEN(403."No relevant authority.");
    
    private long code;
    private String message;

    private ResultCode(long code, String message) {
        this.code = code;
        this.message = message;
    }

    public long getCode(a) {
        return code;
    }

    public String getMessage(a) {
        return message;
    }
Copy the code

This shows you the type of value we’re passing.

Key points: how does this project transmit JSON from front-end to back-end, and network request logic

The types and names of the values passed from the front end to the back end have been explained. Here we discuss the POST process from the front end to the back end:

The logic of the page is nothing to say, one entry, the page is written, the route is configured so that static pages can be accessed one by one.

The key is the vuex and Axios part:

  1. First, run main.js, import store (why not use axios, request will be used later in utils), and then make web requests through Store (store folder is vuex state manager).

  2. Index. js in store is a place to assemble modules and export stores in our project. It is mainly written as const store=new vuex. store (option), which is a fixed Vuex notation

Mutations [type: string], actions,[type: String], modules (modules in store), plugins (Array<Function(store)>, custom plugins), strict, (Boolean, default false), devTools, (Boolean, default false)

(2) For each module, you can create a corresponding semantically oriented.js file (such as test.js) and export the output

(3) Store is divided into multiple sub-modules for convenient development and maintenance.

In new vuex.store ({modules:{m1,m2,m3}}), a module is a normal object.

(4) Js in module

Export default {namespaced:true, Mutations :{}, open mutations:{}, open mutations:{}, open mutations:{}, open mutations:{}, open mutations:{}, open mutations:{}, open mutations:{} }

(5) Plugins are actually functions that take store as their only argument

const store = new Vuex.Store({
  // ...
  plugins: [myPlugin]
})
Copy the code

So what was in the belly of the plugins?

const myPlugin = store => {
  // called when store is initialized
  store.subscribe((mutation, state) => {
    // called after each mutation
    The format of // mutation is {type, payload}})}Copy the code

First of all, Mutation was submitted in the plug-in to generate a State snapshot, which was like a instantly exposed photo and could be used to compare the changes before and after the things taken. To give a general overview, we did not use it in the project, and the official document detailing plugins was not used. Vuex.vuejs.org/zh/guide/pl…

  1. Store makes network requests through the user.js module. The Login method is defined in actions. This method is used in login.vue and the syntax is this.

User.js inside the logic is actually a lot of big guys have written, including before login.vue login logic, nonsense don’t say a look at the code, I took out from the user.js file, I deleted the first sentence import and the last sentence export!

const user = {
    actions: {
        / / login
        // Define the Login method, using the syntax this.$store.dispatch("Login") in the component.
        Login({ commit }, userInfo) {
        	//commit To commit a token later, we do not set it here
            //const username= userinfo.username. Trim (
            const { username, password } = userInfo
            
            // Encapsulate a Promise
            return new Promise((resolve, reject) => {
                // Use the login interface for network requests
                login(username, password).then(response => {
                    commit(' ') // submit a mutation to inform of a state change
                    resolve(response) // Encapsulate the result into a Promise
                }).catch(error => {
                    reject(error)
                })
            })
        },
    }
}
Copy the code

Trim (); const {username, password} =userInfo; Commit in order to later commit a token, we don’t set it here, the token is a local validation thing.

There are some bad code written on the Internet is very misleading, although I write is not very good, but I have explained, without explaining it is really easy to mislead others.

  1. Then user.js uses the LOGIN of the API /login.js interface in return Promise to send the network request

  2. Then you’ll notice that the request used in the login interface is utils/request.js

Utils /request.js creates an axios instance with the basic axios configuration:

import axios from 'axios';
import baseUrl from "@/api/baseUrl";

const service = axios.create({
    baseURL:baseUrl,/ / API base_url
    timeout:15000 // Request timeout
})

export default service
Copy the code

The export syntax declares the raw value for exporting functions, objects, and specified files (or modules). The variables in curly braces import correspond to the variables following export

Import request from ‘@/utils/request’ in API /login.js

You can instantiate axios directly, i.e., request quantities in API /login.js, either using AXIos’ get, POST, etc., or you can create the request by passing the configuration to Axios

Axios.create ([config])

Write an instance, and then inside that instance we can write axios([config]).

And then there’s alias

Aliases are provided for all supported request methods for convenience

axios.request(config) axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.post(url[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]])

  1. Access logical order: main.js calls store/index.js calls user.js calls API /login.js calls request.js calls API/baseurl.js

Vuex + Axios part of all source file code

api/baseUrl.js

let baseUrl = "";
let NODE_ENV='dev';
switch (NODE_ENV) { // Note that the variable name is custom
    //process.env.NODE_ENV
    case 'dev':
        baseUrl = "http://localhost:8088/"  // Development environment URL
        break
    case 'serve':
        baseUrl = "http://localhost:8089/"   // Production environment URL
        break
}

export default baseUrl;
Copy the code

api/login.js

import request from '@/utils/request' // Import the wrapped AXIOS request

export function login(username, password) { // Login interface

    return request({ // Use wrapped AXIos for network requests
        url: '/admin/login'.method: 'post'.data: { // The submitted data
            username,
            password
        }
    })
}
Copy the code

store/modules/user.js

import { login } from '@/api/login'

const user = {
    actions: {
        / / login
        // Define the Login method, using the syntax this.$store.dispatch("Login") in the component.
        Login({ commit }, userInfo) {
            //const username= userinfo.username. Trim (
            const { username, password } = userInfo
            // Encapsulate a Promise
            return new Promise((resolve, reject) = > {
                // Use the login interface for network requests
                login(username, password).then(response= > {
                    commit(' ') // submit a mutation to inform of a state change
                    resolve(response) // Encapsulate the result into a Promise
                }).catch(error= > {
                    reject(error)
                })
            })
        },
    }
}
export default user
Copy the code

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import user from "./modules/user"

Vue.use(Vuex)

const store=new Vuex.Store({modules:{user},plugins: []})export default store
Copy the code

utils/request.js

import axios from 'axios';
import baseUrl from "@/api/baseUrl";
//import baseUrl from '.. / API /baseUrl' defines the baseUrl using the environment variable + schema

const service = axios.create({
    baseURL:baseUrl,
    timeout:15000,})export default service
Copy the code

SpringBoot back-end interface logic development

The IDE on the back end is: Intellij IDEA 2020.2

Back-end project directory:

The second figure follows test

Front end: Java annotation development

This problem, can be said from the university assembly language, C, Java, data structure, compilation principle algorithm introduction and so on a series of software bottom technology, in the development of the first encountered is quite confused, before introducing the back-end development, we will first introduce the back-end development of the most basic problems.

What is an annotation?

Java annotations are a new feature introduced in JDK5, and annotations (also known as metadata) give us a formal way to add information to our code that we can easily use at a later point in time.

The annotation type definition specifies a new type, a special interface type.

Since an annotation is a special kind of interface, the @interface keyword is written to indicate the specificity of the annotation to distinguish the annotation definition from the normal interface declaration.

An application can use reflection to get an annotation object for a specified program element, and then use the annotation object to get metadata inside the annotation. Annotations can be used to create documentation, track dependencies in code, and even perform basic compile-time checks.

In layman’s terms, reflection captures annotation information about a class, such as fields and attribute methods under annotations, and then executes specific code based on that information.

Annotations are often used in frameworks, because the code in annotations is already implemented, and you know what they mean and use them

How items carry information

  1. Information is carried through annotations and then read through reflections

  2. Information is carried through files and then read through IO

Meta-annotations and custom annotations

We can also customize annotations. JDK 1.5 provides four standard annotation classes for annotating annotation types, called meta-annotations.

We can use these four meta-annotations to annotate our custom annotation types. Next, we will take a look at each of the four meta-annotations.

  1. @target annotations: Describe the scope of the annotation. Indicate where the annotation modified by Target can be used

  2. @Retention annotations: Describes the Retention range of annotations (how long annotations described by Retention can be retained in the class it modifies).

  3. Documented: Describes whether to preserve annotation information when generating a help document for a class using the Javadoc tool

  4. @Inherited: Make annotations modified by @Inherited Inherited. (If a class uses an annotation modified by @Inherited, its children will automatically have the annotation.)

For the application of meta-annotations, here we will not introduce more, here just say the definition and significance of meta-annotations, want to learn how to use meta-annotations can go to learn.

The role of annotations

  1. Provide information to the compiler: The compiler can use annotations to detect errors and warnings, such as @override (the compiler validates that the method name following @override is owned by your parent class, or an error will be reported if it is not), and @deprecated (indicating that the following method is Deprecated because there are better methods to call).

  2. Compile phase processing: Software tools can be used to generate code from annotation information, Html documents or do other corresponding processing, such as @ Param (@ Param is org. Apache. Ibatis. Annotations. The Param, as an entity class entity/Dao layer annotation, It is used to pass parameters that correspond to field names in SQL. It is best used when 2=< parameter number <=5), @return (instructions for generating JavaDoc), and @author (comments at the beginning of the file generate Author information).

  3. Runtime processing: Some annotations can be extracted while the program is running. It is important to note that annotations are not part of the code itself. Spring 2.5 starts to annotate configuration, reducing configuration.

Particularity of annotation

Once an annotation is defined through @Interface, it cannot inherit from other annotations or interfaces. Annotations do not support extends.

Several special notes

Here are some common annotations. Since there is no table of contents for the level 4 headings, I have changed them to level 3 headings.

@Override

An example of an annotation required by the override method is:

@RequestMapping

@requestMapping is actually a combination of @postMapping and @getMapping. If you are afraid of unnecessary writing errors during the mapping and you don’t know whether the following method is GET or POST, You can write @requestMapping (<=> = equivalent)

@RequestMapping(method = RequestMethod.GET) <=> @GetMapping

@RequestMapping(method = RequestMethod.POST) <=> @PostMapping

The commonly used @RequestMapping consists of seven request methods:

GET (request page information), POST (submit data to a specified resource), HEAD, PUT (client -> server), DELETE (server removes a specified page), CONNECT (pipe connection), OPTIONS (Client view server performance)

@ ResponseBody and @ RequestBody

  1. @ResponseBody

Converts Java objects to jSON-formatted data using methods that write ajax (datAS) requests to User objects

If the return value is a string, the string is written directly to the client; If it is an object, the object is converted to a JSON string and then written to the client.

  1. @RequestBody

As the following example demonstrates, @responseBody and @requestBody work together so that the user object is no longer parsed as a jump path, but written directly into the BODY of the HTTP response

Such as:

@RequestMapping(value = "user/login")
@ResponseBody

public User login(@RequestBody User user) {   

    return user;    
}
Copy the code

@ RestController and @ Controller

@Controller The Controller (injection service) is used to annotate the control layer, equivalent to the Action layer in Struts

@Autowired

I’ll talk about it later in conjunction with @repository, listed here, but I won’t go into details

@Service

@service The @service Service (inject DAO) is used to annotate the Service layer, mainly for the logical processing of business

@ Mapper and @ the Repository

  1. The same

Both @mapper and @Repository operate on dao/ Entity interface, making it generate proxy object bean, which is handed over to Spring container for management. For Mybatis, mapper.xml file is not needed

@repository (implementing DAO/Entity access) is used to annotate the data access layer and, arguably, the data access component, the DAO component

  1. The difference between

(1) @mapper does not need to configure the scanning address. Through the interface address in the namespace of mapper. XML, the Bean is generated and injected into the Service layer.

@mapper does not need to configure the scan address, can be used independently, if there are multiple Mapper files, you can add @mapperscan (” Mapper file package “) in the project startup class, so that every Mapper file does not need to add @mapper annotation

(2) @repository needs to configure the scan address in Spring before generating beans from the Dao layer can be injected into the Service layer.

@repository should not be used alone, otherwise an error will be reported that the bean cannot be found. This is because the file with @repository annotation was not scanned when the project was started, so the scanning address needs to be configured to use @repository.

In idea, using @Repository eliminates errors when injecting Mapper objects into the business layer;

If you do not annotate @repository with value=’ address ‘on top of the Mapper interface class, then you must annotate @AutoWired with @autoWired on top of the interface reference in serviceImpl, as shown below:

@ component and @ MapperScan

Once an annotation about Spring appears in a class, such as when I use the @Autowired annotation in the implementation class, the annotated class is taken from the Spring container, and the implementation class called needs to be managed by the Spring container, with the @Component added

@Component (instantiating regular POJos into the Spring container, which is equivalent to configuration files) is a generic term for components, meaning that when our class doesn’t belong to any of the categories (@Controller, @Service, etc.), we can use @Component to label that class.

Q: Why don’t UserMapper write @Component?

How is the Mapper interface managed by Spring?

  1. The interface is scanned by @mapperscan

  2. Dynamically proxying the interface, all a proxy class does is take the SQL, connect to the database, and execute the SQL

  3. Proxy objects are handed over to Spring for management through the Spring extension mechanism FactoryBean

Mapper package (com.xxx.mapper); mapper package (com.xxx.mapper); mapper package (com.xxx.mapper);

Project initialization

Click File->New->Project in the upper left corner and click according to the arrow

After Next, click on the arrow again, noting that Java Version selects 8

I usually choose the following as the basic dependencies. If the package I want is not included in these columns, I can add them in pom.xml later.

  1. Spring Boot DevTools in Developer Tools
  2. Lombok in Developer Tools
  3. Spring Web within the Web
  4. Spring Security in Security
  5. Spring Data JDBC in SQL

Finally, it comes to the project path selection, choose a put our project files, it is best not to C disk oh, C disk full of words is very headache! Then click Finish!

Now it’s time to write the back-end file

Pom. Writing XML

If you are working on a back-end project by following the steps ABOVE, the following dependencies must appear in the POM.xml file, each with an artifactId

  1. Spring-boot-starter -parent: this dependency version, mine is 2.4.1, is the parent of Spring Boot (total dependency), which means the current project is a Spring Boot project. Spring-boot-starter-parent is a special starter that provides associated Maven default dependencies.

  2. Properties, declare our Java JDK version, usually 1.8

  3. In dependencies, spring-boot-starter-web When the project is started, the embedded Tomcat is used as a Web container to provide HTTP services. The @Configuration configuration class that provides the annotation @EnableWebMVC takes over all SpringMVC configuration completely, and Converter and Formatter are registered with the IOC container

The purpose of POM.xml:

POM, short for Project Object Model, is a file in the Maven Project, represented in XML and named POM.xml. This file is used to manage: source code, configuration files, developer information and roles, problem tracking systems, organizational information, project authorization, project urls, project dependencies, and so on. In fact, in the Maven world, a project can have nothing, not even code, but must include the POM.xml file.

Pom.xml can be written more, but it must not be written less

The pom.xml for this project is as follows:

<? 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0. 0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId>  <version>2.41.</version> <relativePath/> <! -- lookup parent from repository --> </parent> <groupId>cn.eli.vue</groupId> <artifactId>vue-login-java</artifactId> <version>0.01.-SNAPSHOT</version>
	<name>vue-login-java</name>
	<description>Vue Login Java</description>

	<properties>
		<java.version>1.8</java.version> </properties> <dependencies> <! --mp--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.2. 0</version> </dependency> <! --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.2. 0</version>
		</dependency>


		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency> <! --mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins>  <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties 
      
       **/
      *.xml</include>
					<include>**/*.yml  
      
       false
        
       
       
        src/main/resources
        
        
        
         **/
        
       
      *.yml</include>
					<include>**/*.properties 
      
       **/
      *.xml</include>
				</includes>
				<filtering>false</filtering>
			</resource>

		</resources>

	</build>

</project>

Copy the code

Some of the poM dependencies are represented in the Project section of the Spring Initializr large tag: dependencies for this project

When declaring, the version tag can be omitted. Why not? The spring-boot-starter-parent tag will provide the version of the jar package that is usually used by the parent tag. You can also specify a version number, which overwrites the official version. Use Maven Helper to check for conflicts.

Spring-boot-devtools, Lombok, spring-boot-starter-data-jdbc are not used in this project, I generally introduce them.

  1. mybatis-plus-boot-starter

Mybatis required package

  1. mybatis-plus-generator

Mybatis required package

  1. Spring-boot-starter-web: This was explained above.

  2. Spring – the boot – devtools: Devtools implements hot deployment of the page (the page changes take effect immediately, which can be done directly by setting spring.thymeleaf.cache=false in the application.properties file), and hot deployment of the class files (the class file changes do not take effect immediately). Implement hot deployment of properties files.

  3. Lombok: Generate an abstract syntax tree AST from code (see Data Structures)

Here’s a simple example:

When we build an entity class, we tend to automatically generate all of its basic operations. That’s definitely how we started

public class Mountain{
    private String name;
    private double longitude;
    private String country;
}
Copy the code

Now that we have Lombok, let’s add an @data annotation

@Data
public class Mountain{
    private String name;
    private double longitude;
    private String country;
}
Copy the code

We will find that

Thief JB convenient right!

There are several common uses of annotations in Lombok, as follows.

@getter / @setter: Used on a class to generate Getter/ Setter methods for all member variables

ToString: Applies to a class, overriding the default ToString () method, which can restrict the display of certain fields via the of attribute

@equalsandHashCode: applied to the class, overriding the default equals and hashCode methods

@nonNULL: applies to member variables and parameters. The identifier cannot be null. Otherwise, a null pointer exception is thrown

@data: Applies to a class and is a collection of annotations: @toString @equalSandhashCode @getter @setter @requiredargsconstructor

  1. Spring – the boot – starter – data – JDBC:

Spring Data includes repository support for JDBC and will automatically generate SQL for methods on CrudRepository. Spring Boot will automatically configure Spring Data’s JDBC repository when the necessary dependencies exist on the CLASspath.

After the introduction of this package, you can operate the database through the method (here I do not speak, want to learn their own information, because I am not commonly used, the project is not used!) Of course, you don’t have to use the XML operation database

In my opinion, the purpose of this package is to give the configuration syntax for the data source: add the application.properties configuration file to the SRC /main/resource directory, which reads as follows:

spring.datasource.url = jdbc:mysql://localhost:3306/test? serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
Copy the code

All right, that’s what yML is about.

  1. Mysql connector – Java:

JAVA requires this package to access the mySQL database through JDBC.

Here said the first version of this package problem, because he had mysql8 and mysql5 version project out of the question so suddenly, thief tired, you must first understand yourself before you write the program of the project is to be used 5 or 8

(1) mysql-connector-java

(2) mysql-connector-java

  1. Spring – the boot – starter – test:

When the project is automatically generated, it comes with a test class. I didn’t delete it

Defines the return class Result and API opcodes

General return object, API interface opcode, these online has a uniform format specification, it is recommended that students understand a writing method has been used.

Here I talk about my use of a set of writing, this thing is supporting, to use a set, do not go to the east with the west, it is easy to go wrong.

Return the result class and the API opcode, which I put under a package called API in the following directory:

OK, now start putting the code in. Ow!

  1. CommonResult. Java (class)
package cn.eli.vue.api;

/ * * *@author: Laboratory *@Date: the 2021-1-15 11:33:26 *@Description: * /
public class CommonResult<T> {
    private long code;
    private String message;
    private T data;

    protected CommonResult(a) {}protected CommonResult(long code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    /** * Successfully returns the result **@paramData Obtained data */
    public static <T> CommonResult<T> success(T data) {
        return new CommonResult<T>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
    }

    /** * Successfully returns the result **@paramData Indicates the obtained data *@paramMessage Indicates the prompt message */
    public static <T> CommonResult<T> success(T data, String message) {
        return new CommonResult<T>(ResultCode.SUCCESS.getCode(), message, data);
    }

    /** * Returns a result **@paramErrorCode indicates the errorCode */
    public static <T> CommonResult<T> failed(IErrorCode errorCode) {
        return new CommonResult<T>(errorCode.getCode(), errorCode.getMessage(), null);
    }

    /** * Returns a result **@paramMessage Indicates the prompt message */
    public static <T> CommonResult<T> failed(String message) {
        return new CommonResult<T>(ResultCode.FAILED.getCode(), message, null);
    }

    /** * Failed to return the result */
    public static <T> CommonResult<T> failed(a) {
        return failed(ResultCode.FAILED);
    }

    /** * Parameter verification failure Result */
    public static <T> CommonResult<T> validateFailed(a) {
        return failed(ResultCode.VALIDATE_FAILED);
    }

    /** * Parameter verification failed result **@paramMessage Indicates the prompt message */
    public static <T> CommonResult<T> validateFailed(String message) {
        return new CommonResult<T>(ResultCode.VALIDATE_FAILED.getCode(), message, null);
    }

    /** * No login result */
    public static <T> CommonResult<T> unauthorized(T data) {
        return new CommonResult<T>(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage(), data);
    }

    /** * Unauthorized return result */
    public static <T> CommonResult<T> forbidden(T data) {
        return new CommonResult<T>(ResultCode.FORBIDDEN.getCode(), ResultCode.FORBIDDEN.getMessage(), data);
    }

    public long getCode(a) {
        return code;
    }

    public void setCode(long code) {
        this.code = code;
    }

    public String getMessage(a) {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData(a) {
        return data;
    }

    public void setData(T data) {
        this.data = data; }}Copy the code
  1. Ierrorcode.java (interface)
package cn.eli.vue.api;

/ * * *@author: Laboratory *@Date: the 2021-1-15 11:33:26 *@Description: * /
public interface IErrorCode {
    long getCode(a);
    String getMessage(a);
}

Copy the code
  1. The ResultCode. Java (class)
package cn.eli.vue.api;

/ * * *@author: Laboratory *@Date: the 2021-1-15 11:33:26 *@Description: * /
public enum ResultCode implements IErrorCode {
    SUCCESS(200."Operation successful"),
    FAILED(500."Operation failed"),
    VALIDATE_FAILED(404."Parameter verification failed"),
    UNAUTHORIZED(401."Not logged in or token has expired"),
    FORBIDDEN(403."No relevant authority.");
    private long code;
    private String message;

    private ResultCode(long code, String message) {
        this.code = code;
        this.message = message;
    }

    public long getCode(a) {
        return code;
    }

    public String getMessage(a) {
        returnmessage; }}Copy the code

Backend resolution of cross-domain requests CorsConfig

For the processing of cross-domain request, we will process it at the back end, and the code directory is as follows:

The detailed principle of cross-domain request please own hundred degrees, here I only explain how to use

File: CorsConfig. Java

Code:

package cn.eli.vue.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;

/ * * *@author: Laboratory *@Date: the 2021-1-15 11:33:26 *@Description: * /
@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig(a) {
        System.out.println("222222222222");
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); / / 1
        corsConfiguration.addAllowedHeader("*"); / / 2
        corsConfiguration.addAllowedMethod("*"); / / 3
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter(a) {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/ * *", buildConfig()); / / 4
        return newCorsFilter(source); }}Copy the code

Write user in the entity class Entity

Everyone knows springBoot’s business logic:

The entity class User interacts with the database on the Mapper interface from the Controller according to the logic in the Service

We first wrote the entity class Dao/ Entity, defined the basic method of user entity, and then developed the corresponding MAPper interface and database operation according to the login function, namely the XML corresponding to mapper. After writing, Then write the basic service interface and the implementation of the service (i.e., the Impl). Finally, write the login controller, which is easy or difficult.

The user.java entity class is simple and the directory logic is as follows:

The user.java code is as follows, without any annotations, just basic get and set. If you don’t want to write it yourself, you can implement it automatically using the Lombok package I described above.

package cn.eli.vue.entity;
//import lombok.Data;
/ * * *@author: Laboratory *@Date: the 2021-1-15 11:33:26 *@Description: * /
public class User {

    private int id;

    private String username;

    private String password;

    public int getId(a) {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername(a) {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword(a) {
        return password;
    }

    public void setPassword(String password) {
        this.password = password; }}Copy the code

Mapper layer and Service layer development

The directory logic of the mapper and service layers is as follows:

The mapper layer

  1. Usermapper.java (User interface)
package cn.eli.vue.mapper;


import cn.eli.vue.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
//import org.springframework.stereotype.Component;
//import org.springframework.stereotype.Repository;

/ * * *@author: Laboratory *@Date: the 2021-1-15 11:33:26 *@Description: * /

@Mapper
public interface UserMapper {
    public User Login(@Param("username") String username, @Param("password") String password);
    //public User Login(String username,String password);
}

Copy the code
  1. Usermapper.xml (SQL for user operation database)
<? xml version="1.0" encoding="UTF-8"? > <! --@author: Lab --> <! --@Date: 2021-1-15 11:33:26-- > <! --@Description: -- -- > <! DOCTYPE mapper PUBLIC"- / / mybatis.org//DTD Mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="cn.eli.vue.mapper.UserMapper">
<select id="Login" resultType="cn.eli.vue.entity.User">
    select * from userlink where username = #{username} and password = #{password}
</select>
</mapper>

Copy the code

The service layer

  1. Service layer interface: userService.java
package cn.eli.vue.service;

import cn.eli.vue.entity.User;


/ * * *@author: Laboratory *@Date: the 2021-1-15 11:33:26 *@Description: * /

public interface UserService {
    public User Login(String username,String password);
}
Copy the code
  1. Implementation of the Service layer interface: UserServicePl.java
package cn.eli.vue.service.impl;

import cn.eli.vue.entity.User;
import cn.eli.vue.mapper.UserMapper;
import cn.eli.vue.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/ * * *@author: Laboratory *@Date: the 2021-1-15 11:33:26 *@Description: * /

@Service("UserService")
public class UserServiceImpl implements UserService{
    @Autowired
    UserMapper userMapper;

    @Override
    public User Login(String username,String password){

        returnuserMapper.Login(username,password); }}Copy the code

Controller layer business logic development

Controller layer directory logic:

LoginController.java

package cn.eli.vue.controller;

import cn.eli.vue.api.CommonResult;
import cn.eli.vue.entity.User;
import cn.eli.vue.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/ * * *@author: Laboratory *@Date: the 2021-1-15 11:33:26 *@Description: * /
@ResponseBody
@RestController
public class LoginController {
    @Autowired
    UserService userService;

    @RequestMapping(value = "/admin/login")
    public CommonResult login(@RequestBody User user) {

        //String username= request.getParameter("username");
        //String password= request.getParameter("password");
        String username=user.getUsername();
        String password=user.getPassword();

		// Output test
        System.out.println("11111111");
        System.out.println(username);
        System.out.println(password);

        user=userService.Login(username,password);
        if(user! =null) {return CommonResult.success("admin");
        }
        else{
            return CommonResult.validateFailed("1"); }}}Copy the code

Modify VueLoginJavaApplication

Directory logic:

VueLoginJavaApplication. Java code:

package cn.eli.vue;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/ * * *@author: Laboratory *@Date: the 2021-1-15 11:33:26 *@Description: * /
@SpringBootApplication
@MapperScan("cn.eli.vue.mapper")
public class VueLoginJavaApplication {

	public static void main(String[] args) { SpringApplication.run(VueLoginJavaApplication.class, args); }}Copy the code

The overall configuration of the project application. Yml

Overall project configuration Directory logic:

server:
  port: 8088

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
#    url: jdbc:mysql: / /localhost: 3306 /denglu_sp?serverTimezone=GMT%2B8
    url: jdbc:mysql://localhost:3306/denglu_sp? serverTimezone=UTCUsername: root password: wcq980220 # hot deployment in force the spring. The devtools. Restart. Enabled:true
Copy the code

Postman performs back-end data POST tests

Let’s start with postman for our back-end tests

Maven pit, detailed explanation (welcome to contribute to me, I will continue to add here)

First of all, this is my own collation of this project encountered some small problems, very simple, big guy do not spray!

  1. Dependency in Maven will appear as a red wavy line.

< span style = “box-sizing: border-box; color: RGB (51, 51, 51); line-height: 22px; font-size: 14px! Important; word-break: inherit! Important;”

(2) Click Reload All Maven Projects.

(3) You will find that the dependency folder disappears directly, indicating that the annotation is successful;

(4) At this point, uncomment the dependency, Reload All Maven Projects, and let the dependency be reimported

  1. Maven-packed target file is always running error, check syntax is correct, what to do?

(1) Check whether mapper contains XML

(2) Check whether application.yml is available

(3) Solution: pom. XML in the requirements of packaging when mandatory with suffix yML and XML file (this I have brought the above source code, you can go to see)

Local JavaWeb application pulled up, project running (video recording writing!!)

The cloud server goes online

Configure the CentOS environment based on Linux

Pull up Redis, nginx, mysql

Deploy the JAR and the front-end page