一、环境准备
此次实验需要的环境: jdk、maven、nvm和node.js
开发工具:idea或者Spring Tool Suite 4,前端可使用HBuilder X,数据库Mysql
下面提供maven安装与配置步骤和nvm安装与配置步骤:
1、maven安装与配置
1.1 下载maven包
https://dlcdn.apache.org/maven/maven-3/3.9.5/binaries/apache-maven-3.9.5-bin.zip
1.2 解压到安装目录
1.3 将maven目录配置成环境变量
1.4 Cmd打开命令窗口,验证maven: mvn -v
1.5 配置setting文件 打开maven目录,找到conf目录下setting.xml ,修改默认仓库路径
二、nvm安装与配置
1、NVM简介
在项目开发过程中,使用到vue框架技术,需要安装node下载项目依赖,但经常会遇到node版本不匹配 而导致无法正常下载,重新安装node却又很麻烦。为解决以上问题,nvm:一款node的版本管理工 具,能够管理node的安装和使用,使用简单,可下载指定node版本和切换使用不同版本,方便了node 的使用。
2、NVM安装
2.1 下载
安装包下载地址: https://github.com/coreybutler/nvm-windows/releases
windows系统下载nvm-setup.exe
2.2 安装
双击nvm-setup.exe开始安装(安装之前最好卸载计算机已经安装的node)
选择nvm安装根路径
指定nodejs的安装路径(最好提前新建nodejs文件夹,在安装时选择)
2.3 测试
打开命令行,输入nvm -v 可查看版本,即安装成功
3、NVM使用
3.1 设置
设置下载源,修改setting.txt 在安装根路径下编辑setting.txt
添加以下两行镜像地址:
node_mirror:https://npm.taobao.org/mirrors/node/
npm_mirror: https://npm.taobao.org/mirrors/npm/
3.2 使用
1. nvm list available 显示可以安装的所有node.js的版本
2. nvm install 16.20.0 安装node.js的命名 version是版本
3. nvm list 查看已安装的node.js
4. nvm use 16.20.0 切换到使用指定的nodejs版本
*** 表示当前使用的node版本是16.20.0
3.3 NVM常用命令
nvm off // 禁用node.js版本管理(不卸载任何东西)
nvm on // 启用node.js版本管理
nvm install // 安装node.js的命名,version是版本号 例如:nvm install 8.12.0
nvm uninstall // 卸载node.js是的命令,卸载指定版本的nodejs,当安装失败时卸载使用
nvm ls // 显示所有安装的node.js版本
nvm list available // 显示可以安装的所有node.js的版本
nvm use // 切换到使用指定的nodejs版本
nvm v // 显示nvm版本
nvm install stable // 安装最新稳定版
3.4 NVM常见异常
1.nvm use失效 无法使用node
原因:在安装nvm的时候修改了nodejs的安装路径,但安装包并未在指定路径新建nodejs 解决:在指定路径手动新建nodejs文件夹,重新安装并指定路径
三、搭建前后端分离项目
1、后端项目
1.1 数据库设计
1.2 新建springboot工程
第一种方式使用idea创建,File ---> New Project ---> Spring Initializr ,选择对应的配置。
如果idea没有Spring Initializr ,或者本地jdk不支持Spring Initializr中jdk的选项可以采用第二种方式,访问https://start.aliyun.com/
选择对应的配置,获取代码,然后导入idea或Spring Tool Suite 4
1.3 项目结构以及代码
项目的总体结构如图:
pom.xml文件
<?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.8</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>springbootvue</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springbootvue</name>
<description>Demo project for Spring Boot</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>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-core</artifactId>
<version>3.5.3</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
application.yml
spring:
datasource:
username: root
password: 1qaz@WSX3edc
url: jdbc:mysql://localhost:3306/course2023?
allowMultiQueries=true&characterEncoding=UTF-8&characterSetResults=UTF
8&zeroDateTimeBehavior=convertToNull&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
server:
port: 8181
mybatis:
type-aliases-package: com.example.springbootvue.entity
mapper-locations: classpath:mapper/*.xml
UserController.java
package com.example.springbootvue.controller;
import com.example.springbootvue.entity.user;
import com.example.springbootvue.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
@GetMapping("/findAll")
public List<user> findAll() {
return userService.queryuserList();
}
@GetMapping("/")
public String test() {
return "test";
}
@PostMapping("/login")
public user login(@RequestParam("username") String username,
@RequestParam("password") String password) {
return userService.queryUserByNameAndPwd(username, password);
}
}
user.java
package com.example.springbootvue.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class user {
private Integer id;
private String username;
private String password;
}
UserMapper.java
package com.example.springbootvue.mapper;
import com.example.springbootvue.entity.user;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface UserMapper {
public List<user> queryuserList();
public user queryUserByNameAndPwd(@Param("username")String username,
@Param("password")String password);
}
UserService.java
package com.example.springbootvue.service;
import com.example.springbootvue.entity.user;
import java.util.List;
public interface UserService {
public List<user> queryuserList();
public user queryUserByNameAndPwd(String username,String password);
}
UserServiceImpl.java
package com.example.springbootvue.service;
import com.example.springbootvue.entity.user;
import com.example.springbootvue.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserMapper userMapper;
@Override
public List<user> queryuserList() {
return userMapper.queryuserList();
}
@Override
public user queryUserByNameAndPwd(String username, String password) {
return userMapper.queryUserByNameAndPwd(username,password);
}
}
usermapper.xml
<?xml version="1.0" encoding="UTF8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.springbootvue.mapper.UserMapper">
<select id="queryuserList"
resultType="com.example.springbootvue.entity.user">
select * from user
</select>
<select id="queryUserByNameAndPwd"
resultType="com.example.springbootvue.entity.user">
select * from user where username=#{username} and password = #{password}
</select>
</mapper>
CrosConfig.java
package com.example.springbootvue.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CrosConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry){
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
运行SpringbootvueApplication.java,启动成功后,在浏览器上面访问localhost:8181/user/
2、前端项目
2.1 创建vue项目
首先创建一个文件夹,在地址栏输入cmd,按回车键,会出现下面的命令行窗口
输入npm -v和node -v 查看是否安装
接着输入npm install -g @vue/cli来安装相关插件,如果出现如下图错误,是因为npm的官方源在国 外,下载很慢,下面我们将npm源切换成国内源。
下载淘宝镜像源:npm install -g cnpm --registry=https://registry.npm.taobao.org
把当前的源切换成淘宝的源:npm config set registry https://registry.npm.taobao.org
查看源是否切换成功:npm config get registry
继续安装npm install -g @vue/cli
安装好之后输入vue create myfirst(myfirst是你要创建的项目的名称),回车。然后进入下图界面,选 择第三个,回车。
接着选择下图所示选项(上下箭头移动,空格键选中),接着回车
然后后面按我下图所选的即可
接着会加载一段时间(稍微等待一下)
然后我们可以按它的提示输入:
cd myfirst
npm run serve
在浏览器输入生成的链接得到下图,此时vue项目搭建完成
2.2 构建一个简单的登录界面
修改router文件夹下面的index.js如下
import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import login from "@/views/login";
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'login',
component: login
},
{
path: '/home',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
component: () => import(/* webpackChunkName: "about" */
'../views/AboutView.vue')
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
修改views文件夹下面的HomeView.vue如下
<template>
<div class="home">
{{ username }} 登录成功
</div>
</template>
<script>
export default {
data() {
return {
}
},
created() {
this.username = this.$route.query.username
},
}
</script>
<style>
</style>
在views文件夹下创建login.vue
<template>
<div class="login">
<div class="mylogin" align="center">
<h4>登录</h4>
<el-form
:model="loginForm"
:rules="loginRules"
ref="loginForm"
label-width="0px"
>
<el-form-item label="" prop="account" style="margin-top: 10px">
<el-row>
<el-col :span="2">
<span class="el-icon-s-custom"></span>
</el-col>
<el-col :span="22">
<el-input
class="inps"
placeholder="账号"
v-model="loginForm.account"
>
</el-input>
</el-col>
</el-row>
</el-form-item>
<el-form-item label="" prop="passWord">
<el-row>
<el-col :span="2">
<span class="el-icon-lock"></span>
</el-col>
<el-col :span="22">
<el-input
class="inps"
type="password"
placeholder="密码"
v-model="loginForm.passWord"
></el-input>
</el-col>
</el-row>
</el-form-item>
<el-form-item style="margin-top: 55px">
<el-button type="primary" round class="submitBtn" @click="submitForm"
>登录
</el-button>
</el-form-item>
<div class="unlogin">
<router-link :to="{ path: '/forgetpwd' }"> 忘记密码? </router-link>
|
<router-link :to="{ path: '/register' }">
<a href="register.vue" target="_blank" align="right">注册新账号</a>
</router-link>
</div>
</el-form>
</div>
</div>
</template>
<script>
import { mapMutations } from "vuex";
import axios from 'axios'
export default {
name: "Login",
data: function () {
return {
loginForm: {
account: "",
passWord: "",
},
loginRules: {
account: [{ required: true, message: "请输入账号", trigger: "blur" }],
passWord: [{ required: true, message: "请输入密码", trigger: "blur" }],
},
};
},
methods: {
...mapMutations(["changeLogin"]),
submitForm() {
const userAccount = this.loginForm.account;
const userPassword = this.loginForm.passWord;
const params = new URLSearchParams();
params.append('username', userAccount);
params.append('password', userPassword);
// 发起一个post请求
axios({
method: 'post',
url: 'http://localhost:8181/user/login',
params: params
}).then(resp=>{
console.log(resp.data);
if(resp.data != null && resp.data.id != null){
this.$router.push('/home?username='+resp.data.username);
}else{
this.$message({
message: '账户不存在或密码错误',
type: 'warning'
});
}
});
console.log("用户输入的账号为:", userAccount);
console.log("用户输入的密码为:", userPassword);
},
},
};
</script>
<style>
.login {
height: 100vh;
background-image: linear-gradient(to bottom right, #3F5EFB, #42b983);
overflow: hidden;
width: 100vw;
padding: 0;
margin: 0;
font-size: 16px;
background-position: left top;
background-color: #242645;
color: #fff;
position: relative;
}
.mylogin {
width: 240px;
height: 280px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
padding: 50px 40px 40px 40px;
box-shadow: -15px 15px 15px rgba(6, 17, 47, 0.7);
opacity: 1;
background: linear-gradient(
230deg,
rgba(53, 57, 74, 0) 0%,
rgb(0, 0, 0) 100%
);
}
.inps input {
border: none;
color: #fff;
background-color: transparent;
font-size: 12px;
}
.submitBtn {
background-color: transparent;
color: #39f;
width: 200px;
}
</style>
login.vue要用到axios和element-ui,所以我们要安装axios和element-ui
npm install axios
npm install element-ui -S
在main.js中引入element-ui
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
axios可以在对应的页面引入
import axios from 'axios'
App.vue修改如下
<template>
<div id="app">
<router-view/>
</div>
</template>
在终端输入指令npm run serve运行vue项目,点击生成的链接即可,然后输入账号和密码进行登录,登录后进入主页面
四、完成用户注册和查询功能
用户注册功能效果图如下:
点击注册新账号,跳转到注册页面
填写新账户密码,点击注册,注册成功之后跳转到登录页面,用新账户登录可以登录成功 查询功能效果:在登陆成功页面添加查询按钮
点击查询按钮,查询所有账户,效果如图所示