Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

Author’s other platforms:

| CSDN:blog.csdn.net/qq_4115394…

| the nuggets: juejin. Cn/user / 651387…

| zhihu: www.zhihu.com/people/1024…

| GitHub:github.com/JiangXia-10…

| public no. : 1024 notes

This article is about 11,088 words and takes 29 minutes to read

1 introduction

At present, the development mode of many companies is separated before and after the division of labor mode, so that each can do its own job, improve the efficiency of development. Previous articles have described creating a simple front-end project with Springboot and Vue. This article is about a simple integration of Springboot and Vue to implement a simple login page.

Finally, the source of this article will be synchronized to Github, welcome to download and use star!

2 the body

First, let’s introduce the development tools of this paper. The Java version used in the back end is JDK1.8, the framework is Springboot, the development tool is IDEA, the front end is vue.js, and the development tool is VS Code.

The prerequisite for this article is a brief understanding of SpringBoot and vue.js.

For details on how to create a Springboot project using IDEA, see: Getting Started with Springboot: Build your first Springboot project using IDEA and Eclipse.

How to create a VUE front-end project can refer to: VUE learning Notes (a) : create a VUE front-end project from scratch.

I. Back-end Springboot project development:

Select * from user where user = ‘user’;

CREATE TABLE 'user' (' id 'int(11) NOT NULL AUTO_INCREMENT COMMENT' id ', 'email' varchar(255) NOT NULL COMMENT 'id ', 'password' varchar(255) NOT NULL COMMENT 'id ',' username 'varchar(255) NOT NULL COMMENT' id ', 'PRIMARY KEY ', UNIQUE KEY `email` (`email`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; INSERT INTO 'user' VALUES ('1', '[email protected]', '123456', '123456'); INSERT INTO 'user' VALUES ('2', '[email protected]', '234567'); INSERT INTO ` user ` VALUES (' 3 ', '3 @qq.com', '345678', 'Cathy');Copy the code

Start by creating a SpringBoot project and then introduce the dependencies in the POM file:

<? The 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 > < the parent > < groupId > org. Springframework. Boot < / groupId > The < artifactId > spring - the boot - starter - parent < / artifactId > < version > 2.3.2. RELEASE < / version > < relativePath / > <! -- lookup parent from repository --> </parent> <groupId>com.springboot</groupId> <artifactId>springbootdemo</artifactId> <version>0.0.1-SNAPSHOT</version> <name> Springbootdemo </name> <description>Demo project for Spring Boot</description> < properties > < project. Build. SourceEncoding > utf-8 < / project. Build. SourceEncoding > < Java version > 1.8 < / Java version > </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <! <dependency> <groupId>org.mybatis. Boot </groupId> < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 1.2.0 < / version > < / dependency > <! --> <dependency> <groupId> MySQL </groupId> <artifactId>mysql-connector-java</artifactId> The < version > 5.1.39 < / version > < / dependency > <! --> <dependency> <groupId> Commons -io</artifactId> <version>2.5</version> </dependency> </dependencies> <build> <plugins> <! Spring-boot-devtools restarts automatically when a file in the classpath changes. --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> </configuration> </plugin> </plugins> </build> </project>Copy the code

Properties file, add the following configuration:

# # data source configuration spring. The datasource. Url = JDBC: mysql: / / localhost: 3306 / JDBC? useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false spring.datasource.username=root Spring. The datasource. Password = jiang spring. The datasource. The driver - class - name = com. Mysql. JDBC. Driver # # # is configured to Mybatis configuration Com.pancm. bean points to the entity class package path. Mybatis. TypeAliasesPackage = com. Springboot. # bean configuration for the classpath directory path mapper package, * representatives will scan all the XML document. mybatis.mapperLocations=classpath\:mapper/*.xmlCopy the code

Start writing core logic code:

Create a new user.java entity class with the following code:

package com.springboot.springbootdemo.bean; public class User { private long id; private String email; private String password; private String username; public long getId() { return id; } public void setId(int id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; }}Copy the code

Then create a new DAO file:

package com.springboot.springbootdemo.dao; import com.springboot.springbootdemo.bean.User; import org.apache.ibatis.annotations.*; import org.springframework.data.repository.query.Param; import java.util.List; @ Mapper public interface UserDao {/ * * * * / @ Insert new data (" Insert into user values (id, email, password, username) (#{id},#{email},#{password},#{username})") void addUser(User user); */ @update (" Update user set username=#{username},password=#{password} where ID =#{id}") void updateUser(user user); /** * Delete data */ @delete (" Delete from user where id=#{id}") void deleteUser(int id); / * * * * * according to query data / @ the Select (" Select id, email, password, username from the user where the username = # {username} ") to the user findByName(@Param("userName") String userName); / * * * * / @ the Select query all data (" Select id, email, password, username FROM the user ") List < user > the.findall (); }Copy the code

Then there are the service and UserServiceImpl files:

userservice:

package com.springboot.springbootdemo.service; import com.springboot.springbootdemo.bean.User; import java.util.List; Public interface UserService {/** * new user * @param user * @return */ Boolean addUser(user user); /** * change user * @param user * @return */ Boolean updateUser(user user); /** * deleteUser * @param id * @return */ Boolean deleteUser(int id); @param userName */ User findUserByName(String userName); @return */ List<User> findAll(); }Copy the code

UserServiceImpl file:

package com.springboot.springbootdemo.service; import com.springboot.springbootdemo.bean.User; import com.springboot.springbootdemo.dao.UserDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public boolean addUser(User user) { boolean flag=false; try{ userDao.addUser(user); flag=true; }catch(Exception e){ e.printStackTrace(); } return flag; } @Override public boolean updateUser(User user) { boolean flag=false; try{ userDao.updateUser(user); flag=true; }catch(Exception e){ e.printStackTrace(); } return flag; } @Override public boolean deleteUser(int id) { boolean flag=false; try{ userDao.deleteUser(id); flag=true; }catch(Exception e){ e.printStackTrace(); } return flag; } @Override public User findUserByName(String userName) { return userDao.findByName(userName); } @Override public List<User> findAll() { return userDao.findAll(); }}Copy the code

Finally, the controller file:

package com.springboot.springbootdemo.controller; import com.springboot.springbootdemo.bean.User; import com.springboot.springbootdemo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping(value = "/do/user") public class UserController { @Autowired private UserService userService; @RequestMapping(value = "/user", Method = requestMethod.post) public Boolean addUser(@requestBody User User) {system.out.println (" add data: "); return userService.addUser(user); } @RequestMapping(value = "/user", Method = requestMethod.put) public Boolean updateUser(@requestBody User User) {system.out.println (" update data: "); return userService.updateUser(user); } @RequestMapping(value = "/user", method = RequestMethod.DELETE) public boolean delete(@RequestParam(value = "id", Required = true) int Id) {system.out.println (" Delete data: "); return userService.deleteUser(Id); } @RequestMapping(value = "/user", method = RequestMethod.GET) public User findByUserName(@RequestParam(value = "userName", Required = true) String userName) {system.out.println (" query data: "); return userService.findUserByName(userName); } @RequestMapping(value = "/userAll", Method = requestmethod.get) public List<User> findByUserAge() {system.out.println (" query all data :"); return userService.findAll(); }}Copy the code

Then start the project and test it:

Here the back-end interface is basically developed, and then the development of the front-end VUE project.

Ii. Front-end Vue Project development:

The front-end development here is based on the demo from the previous article.

To introduce some components, enter the following command in the terminal window:

CNPM install axios --save-devCopy the code

Then add it to main.js, which looks like this:

// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import './plugins/element.js' // import axios 16 import axios from 'axios' 17 vue.prototype.$ajax = axios vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' })Copy the code

Then create a new page under the Componment folder:

<template> <div class="layout"> <Layout> <Content :style="{padding: '0 50px'}"> <Card> <div style="min-height: 200px;" > <v-table is-horizontal-resize style="width:100%" :columns="columns" :table-data="tableData" row-hover-color="#eee" row-click-color="#edf7ff" ></v-table> </div> </Card> </Content> </Layout> </div> </template> <script> export default { Name: "main-page", data() {return {tableData: [], columns: [{field: 'id', title: 'id', width: 80, titleAlign: 'center', columnAlign: 'center',isResize:true}, {field: 'email', title: 'email', width: 150, titleAlign: 'center', columnAlign: 'center',isResize:true}, {field: 'password', title: 'password', width: 150, titleAlign: 'center', columnAlign: 'center',isResize:true}, {field: 'username', title: 'username', width: 280, titleAlign: 'center', columnAlign: 'left',isResize:true} ] } }, Created () {// Create () {// Create () {// Create () {// Create () {// Create (); The/behind/under the condition of perfect functions to introduce this. $ajax (' http://localhost:8080/do/user/userAll '). Then (res = > {this. TableData = res. Data console.log(res.data); }).catch(function (error) { console.log(error); }); } } </script> <style scoped> .layout{ border: 1px solid #d7dde4; background: #f5f7f9; position: relative; border-radius: 4px; overflow: hidden; height: 100%; } .layout-logo{ width: 100px; height: 30px; background: #5b6270; border-radius: 3px; float: left; position: relative; top: 15px; left: 20px; font-weight: bold; text-align: center; color: #49ffcc; } .layout-nav{ width: 420px; margin: 0 auto; margin-right: 20px; } .layout-footer-center{ text-align: center; } </style>Copy the code

Then add this component to the index.js file:

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import HelloDemo from '@/components/HelloDemo'
import zicomponent from '@/components/zicomponent'
import fucomponent from '@/components/fucomponent'
import MainPage from '@/components/MainPage'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path:'/hello',
      name:'HelloDemo',
      component:HelloDemo
    },
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/zi',
      name: 'zicomponent',
      component: zicomponent
    },
    {
      path: '/fu',
      name: 'fucomponent',
      component: fucomponent
    },
    {
      path: '/main',
      name: 'MainPage',
      component: MainPage
    }
  ]
})

Copy the code

Then type NPM run dev to compile the project:

Note that vue is port 8081 and Springboot is port 8080, so no data can be found.

Here you can see the cross-domain error reported. So we need to do something about the front-end code:

Add the following code to the main.js file:

Prototype.$axios= axios. Defaults. baseURL='/ API 'Copy the code

Config /index.js file, add the following code to proxyTable:

// proxyTable: {'/ API ':{target:"http://localhost:8080/", changeOrigin:true, pathRewrite:{'^/ API ':'}}},Copy the code

Finally restart the front end (I need to restart it in this case otherwise it will not work) and compile:

3 summary

The above is that if you use a simple integration of Springboot and Vue, it will be improved and continued development in the future. Welcome to discuss any questions.

In addition, all the actual combat article source will be synchronized to Github, there is a need to welcome the use of download.

Finally, if you think this article is good, just click “like” and “recommend” to more people.

GitHub source address

The backend: github.com/JiangXia-10…

Front end: github.com/JiangXia-10…

Today’s recommendation

Share some useful tools and self-study sites, suggest collection

Spring Boot develops an interface for uploading images and adding watermarks

Vue Learning Notes (1) : Create a Vue front-end project from scratch

Postman interface test graphic tutorial

JQuery: how to use a selector