一、创建SpringBoot项目
1.项目的pom文件如下所示:
<?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.7.14</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>yonfu</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>yonfu</name>
<description>yonfu</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.application.yml配置文件
spring:
datasource:
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/vue?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
jpa:
hibernate:
ddl-auto: update
show-sql: true
server:
port: 9000
3.创建web全局配置 目前主要是跨域的配置
package com.example.yonfu.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author qx
* @date 2023/8/1
* @des 全局配置
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
/**
* 跨域全局配置
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
// 跨域的来源 *表示所有ip地址
.allowedOrigins("http://localhost:8080")
// *支持所有跨域请求方法
.allowedMethods("*")
// 允许使用数字证书
.allowCredentials(true)
// 允许使用的请求头字段,*表示接受所有字段
.allowedHeaders("*")
// 表示请求响应时效的有效期 单位秒
.maxAge(3600);
}
}
二、创建Vue项目
1.生成Vue项目
node.js的安装请参考其他文章,随后安装vue-cli2 脚手架构建工具(必须在全局中进行安装)在命令行中运行命令 npm install -g vue-cli ,然后等待安装完成。最后在项目目录下,在命令行中运行命令 vue init webpack myVue(初始化一个完整版的项目)。解释一下这个命令,这个命令的意思是初始化一个项目,其中webpack是构建工具,也就是整个项目是基于webpack的。其中myVue是整个项目文件夹的名称,这个文件夹会自动生成在你指定的目录中.
输入命令后,会询问我们几个简单的选项,我们根据自己的需要进行填写就可以了。
Project name :项目名称 ,如果不需要更改直接回车就可以了。注意:这里不能使用大写,所以我把名称改成了vueclitest
Project description:项目描述,默认为A Vue.js project,直接回车,可不用编写。
Author:作者,如果你有配置git的作者,他会读取。
Install vue-router? 是否安装vue的路由插件,我们这里需要安装,所以选择Y
Use ESLint to lint your code? 是否用ESLint来限制你的代码错误和风格。我们这里不需要输入n(建议),如果你是大型团队开发,最好是进行配置。
setup unit tests with Karma + Mocha? 是否需要安装单元测试工具Karma+Mocha,我们这里不需要,所以输入n。
Setup e2e tests with Nightwatch?是否安装e2e来进行用户行为模拟测试,我们这里不需要,所以输入n
2.项目配置
我们使用命令行安装ElementUI和axios到我们的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'
// 导入axios
import axios from 'axios'
// 挂载axios
Vue.prototype.$http = axios
// 设置访问根路径
axios.defaults.baseURL = "http://localhost:9000"
// 导入elementui
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
import './assets/css/global.css'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: {App},
template: '<App/>'
})
3.创建两个组件Login和Home
Login.Vue
<template>
<div class="login_container">
<div class="login_box">
<h2 class="login_title">登录</h2>
<!--用户名-->
<el-form ref="loginFormRef" :rules="rules" class="login_form" :model="loginForm" label-width="80px">
<el-form-item prop="username" label="用户名">
<el-input v-model="loginForm.username" placeholder="用户名"></el-input>
</el-form-item>
<!--密码-->
<el-form-item prop="password" label="密码">
<el-input type="password" v-model="loginForm.password" placeholder="密码"></el-input>
</el-form-item>
<el-form-item class="butns">
<el-button type="primary" @click="onSubmit()">登录</el-button>
<el-button type="info" @click="resetLoginForm()">重置</el-button>
</el-form-item>
</el-form>
</div>
</div>
</template>
<script>
export default {
name: 'Login',
data() {
return {
loginForm: {
username: '',
password: ''
},
// 表单验证规则
rules: {
username: [
{required: true, message: '请输入用户名', trigger: 'blur'},
{min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
],
password: [
{required: true, message: '请输入密码', trigger: 'blur'},
{min: 3, max: 16, message: '密码长度在3-16个字符之间', trigger: 'blur'}
]
}
}
},
methods: {
// 点击登录按钮的方法
onSubmit() {
this.$refs.loginFormRef.validate(async (valid) => {
if (!valid) return;
const {data: res} = await this.$http.post("login", this.loginForm);
console.log(res);
if (res.code === 0) {
this.$message.success("登录成功!!");
// 返回成功 跳转到home页面
this.$router.push({path: '/home'});
// 存储username
window.sessionStorage.setItem("user", this.loginForm.username);
} else {
this.$message.error("登录失败!!!");
}
})
},
// 点击重置按钮的方法
resetLoginForm() {
// 重置 清空表单信息
this.$refs.loginFormRef.resetFields();
}
}
}
</script>
<style scoped>
/*.login_container{
background-image: url(../assets/background.jpg);
height: 100%;
}*/
.login_title {
position: absolute;
left: 50%;
}
.login_box {
width: 450px;
height: 300px;
border-radius: 3px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.butns {
display: flex;
justify-content: flex-end;
}
.login_form {
position: absolute;
bottom: 0;
width: 100%;
padding: 0 10px;
box-sizing: border-box;
}
</style>
Home.vue
<template>
<div>
{{ msg }}
<el-button type="info" @click="logout">退出登录</el-button>
</div>
</template>
<script>
export default {
name: 'Home',
data() {
return {
// 显示session中的用户数据
msg: 'welcome:' + window.sessionStorage.getItem("user")
}
},
methods: {
logout() {
// 跳转到登录页面
this.$router.push("/login");
// 清空session
window.sessionStorage.removeItem("user");
}
}
}
</script>
<style scoped>
</style>
默认生成的App.vue
<template>
<div id="app">
<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>
4.路由配置
在route目录下的index.js文件中进行配置,配置前面创建好的两个组件
import Vue from 'vue'
import Router from 'vue-router'
import Login from "../components/Login.vue";
import Home from "../components/Home.vue";
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
redirect: '/login'
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/home',
name: 'Home',
component: Home
}
]
})
完整的项目结构如图所示:
三、后端逻辑修改
1.创建一个用户实体用于数据的存取
package com.example.yonfu.bean;
import lombok.Data;
/**
* @author qx
* @date 2023/8/2
* @des 用户实体
*/
@Data
public class User {
private String username;
private String password;
}
2.创建一个测试控制层
package com.example.yonfu.controller;
import com.example.yonfu.bean.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* @author qx
* @date 2023/8/2
* @des 控制层
*/
@RestController
public class TestController {
/**
* 登录
*
* @param user 用户请求对象
* @return 登录结果
*/
@PostMapping("/login")
public Map<String, Object> test(@RequestBody User user) {
Map<String, Object> map = new HashMap<>();
// 为了测试方便 就在控制层中写业务逻辑了
if ("admin".equals(user.getUsername()) && "123".equals(user.getPassword())) {
map.put("code", 0);
map.put("msg", "登录成功");
} else {
map.put("code", 1);
map.put("msg", "登录失败");
}
return map;
}
}
3.测试
启动后端项目,先测试数据接口是否返回正常。
四、前端测试
我们进入到前端项目的路径下,使用命令行工具执行命令 npm run dev
执行结束后,显示前端访问路径
我们访问这个路径,默认跳转到登录页面
我们先使用错误的用户名和密码进行登录,会提示登录失败。
接下来我们使用正确的用户名和密码进行登录,登录成功后会跳转到home页面。并且显示登录成功的用户名。
最后我们点击退出登录按钮,跳转到登录页面