Vue+elementui+springboot build a simple front-end and back-end separation framework project
Links to related articles:
Eclipse and IDEA create a Maven Java Web project
Tips before viewing:
The IDEA version used in this article is ultimate 2019.1, and the JDK version is 1.8.0_141.
1. Install node.js
Reference article: Install Node.js on Win10
2. Install cnpm
Because the npm installation plug-in is downloaded from a foreign server, it is greatly affected by the network and may be abnormal, so we need to install the cnpm of Taobao mirror.
Excuting an order
npm install -g cnpm --registry=http://registry.npm.taobao.org
Excuting an order
cnpm -v
You can check the version of cnpm
3. Install vue-cli
Excuting an order
cnpm install -g @vue/cli
Excuting an order
vue -V
You can view the installed version
4. Create a Vue project
Excuting an order
vue create 项目名
Select the default to
enter the projectcd vuedemo
Excuting an order
npm run serve
Visit the
project successfully created.
5. Install related components
5.1 Install element-ui
cnpm install element-ui --save
5.2 Install axios
Axios is a promise-based HTTP library that can be used in browsers and node.js. Can be understood as ajax.
Execute the following command to install axios
cnpm install axios --save
5.3 Install vue-router
Vue Router is the official route manager of Vue.js.
Detailed link URL: Vue Router
Execute the following command to install vue-router
cnpm install vue-router --save
5.4 Install qs
Qs can serialize the object to prevent the data transmitted to the background from not being received.
Execute the following command to install qs
cnpm install qs --save
5.5 Install Vuex
Vuex is a state management mode + library for Vue.js applications. It acts as a centralized store for all components in the application, and its rules ensure that the state can only be changed in a predictable way.
Execute the following command to install Vuex
cnpm install vuex --save
6. IDEA installs the Vue.js plugin
Click File->Settings...
Select Plugins -> search box and enter vue -> Install -> OK -> restart IDEA to make the plugin take effect.
Since I have installed the Vue.js plug-in, it shows Installed.
Click File -> Settings… -> Languages & Frameworks -> JavaScripts -> select ECMAScript 6 in JavaScript language version -> OK
7. IDEA creates an empty project
Select Empty Project->Next to
fill in the project name- >Finish
8. Introduce a new vue project
Introduce the newly created vue project in the Project Structure.
After selecting the project->default the first item Create module from existing sources-Next and
continue to Finish.
Check the package.json file and find that the relevant components are also installed normally.
Run the project
9. New springboot project
Create a new Springboot Module in Project Structure
Reference article: Eclipse and IDEA create a Maven Java Web project Chapter 2.2.1
10. Simple front-end interaction implementation
10.1 Writing a vue project
The directory structure is as follows
Write main.js , introduce element-ui control, router.
import Vue from 'vue'
import App from './App.vue'
import router from './router'
//引入element-ui控件
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.config.productionTip = false
//使用use命令后才起作用
Vue.use(ElementUI)
new Vue({
router,
render: h => h(App),
}).$mount('#app')
Write App.vue .
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<router-view/>
</div>
</template>
<script>
export default {
name: 'App',
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
Write index.js under the router folder
import Vue from 'vue'
import Router from 'vue-router'
//使用懒加载的方式来引入,只有路由被访问的时候才加载
import home from '@/components/Home'
import login from '@/components/Login'
Vue.use(Router)
let router = new Router({
routes: [
{
path:'/',
name :'login',
component:login
},
{
path:'/login',
name :'login',
component:login
},
{
path:'/home',
name :'home',
component:home
}
]
})
export default router
Write the login page Login.vue
<template>
<el-form ref='AccountFrom' :model='account' :rules='rules' lable-position='left' lable-width='0px' class='demo-ruleForm login-container'>
<h3 class="title">登录系统首页</h3>
<el-form-item prop="username">
<el-input type="text" v-model="account.username" auto-complete="off" placeholder="账号"></el-input>
</el-form-item>
<el-form-item prop="pwd">
<el-input type="password" v-model="account.pwd" auto-complete="off" placeholder="密码"></el-input>
</el-form-item>
<el-checkbox v-model="checked" checked class="remember">记住密码</el-checkbox>
<el-form-item style="width:100%;">
<el-button type="primary" style="width:100%;" @click.native.prevent='handleLogin'>登录</el-button>
</el-form-item>
</el-form>
</template>
<script>
import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:8090'
import qs from 'qs';
export default {
name: 'login',
data() {
return {
account: {
username: '',
pwd: ''
},
rules: {
username: [{
required: true,
message: '请输入账号',
trigger: 'blur'
}],
pwd: [{
required: true,
message: '请输入密码',
trigger: 'blur'
}]
},
checked: true
}
},
methods:{
handleLogin(){
this.$refs.AccountFrom.validate((valid)=>{
if(valid){
//将提交的数据进行封装
var param = {username : this.account.username,pwd:this.account.pwd};
axios.post("/system/login", qs.stringify(param)).then((result) => {
if(result.data.code == '200'){
//用vue路由跳转到后台主界面
this.$router.push({path:'/home'});
} else {
this.$message({
message:result.data.msg,
type:'error'
});
}
});
}else{
console.log('error submit');
return false;
}
});
}
}
}
</script>
<style>
body {
background: #DFE9FB;
}
.login-container {
width: 350px;
margin-left: 35%;
}
</style>
Write a successful landing page Home.vue
<template>
<div></div>
</template>
<script>
export default {
mounted: function () {
this.loadData();
},
methods: {
loadData() {
const h = this.$createElement;
this.$notify({
title: '标题名称',
message: h('i', { style: 'color: teal'}, '登录成功')
});
}
}
}
</script>
<style>
body {
background: #DFE9FB;
}
</style>
10.2 Writing a springboot project
Directory Structure
Pom.xml introduces related dependencies
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
Write application.properties
#服务端口配置
server.port=8090
#数据库连接配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useSSL=false&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
#Mybatis配置
mybatis.mapper-locations=classpath:mapper/**.xml
Write DemoApplication.java
package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.demo.dao")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Write CorsFilter.java to solve cross-domain problems
package com.example.demo.filter;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CorsFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requseted-With, Content-Type, Accept");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
Write LoginController.java
package com.example.demo.controller;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/system")
public class LoginController {
@Autowired
private UserService userService;
@PostMapping("/login")
public Map<String, Object> Login(User user){
Map<String, Object> result = new HashMap<>();
User user1 = userService.selectByNameAndPWD(user);
if(user1 == null ){
result.put("code", 500);
result.put("msg", "登录失败");
return result;
}
result.put("code", 200);
result.put("msg", "登录成功");
return result;
}
}
Write UserService.java
package com.example.demo.service;
import com.example.demo.dao.UserMapper;
import com.example.demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User selectByNameAndPWD(User user){
return userMapper.selectByNameAndPWD(user);
}
}
Write UserMapper.java
package com.example.demo.dao;
import com.example.demo.model.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper {
User selectByNameAndPWD(User user);
}
Write User.java
package com.example.demo.model;
public class User {
private String id;
private String username;
private String pwd;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
Write UserMapper.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.dao.UserMapper">
<select id="selectByNameAndPWD" resultType="com.example.demo.model.User" parameterType="com.example.demo.model.User">
select
id,username,pwd
from user
where username = #{username}
and pwd = #{pwd}
</select>
</mapper>
11. Possible problems
11.1 No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
If you encounter the following problems, then you have not dealt with cross-domain issues.
Refer to section 10.2Write CorsFilter.java to solve cross-domain problems Just write a filter.
supplement
Supplement 1 homology and cross-domain
Same source: The same protocol, domain name, and port are the same.
Cross-domain: As long as there is a difference in protocol, domain name, and port, it is cross-domain.
Example: http://www.baidu.com http://
is the protocol, www.baidu.com
the domain name, and 80
the port (the default port can be omitted).
The following is http://demo/login
an example of whether it is of the same origin
http://demo/usr 同源
https://demo/usr 不同源,协议不同
http://a.demo/usr 不同源,域名不同
http://demo:8082/usr 不同源,端口不同