2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Here is a project implementation of vue3+springboot+mybatis+mysql, which simply realizes the login and registration functions separated by front and back ends. The main tools are: idea, navicat
Table of contents
1. Create a Vue3 project and configure it initially
2. Modify the project structure
1) Original directory structure
2) Modified directory structure
Edit and write the login and registration page
5) Login and registration page display
2. Create a springboot+mysql+mybatis project and connect to the database
3. Write login and registration backend functions
To create a project, please refer to one of my articles:
Create a custom vue3 project with IDEA_idea vue3-CSDN blog
Initial directory structure after creation:
First you need to modify the original directory structure
assetsPost pictures
componentsMedium-amplified components, usually reusable
routerIs the routing, where the file paths of all main pages are configured
storeGenerally used for vuex state management, such as storing tokens, etc.
viewsThe main page
App.vueIt is the root component of a Vue application.
main.jsIt is the entry file of the application, usually used to introduce dependencies such as vue and vue router.
To implement the login and registration functions, the modified directory structure is:
Create LoginAndRegister.vue in the components folder to implement the login and registration page and functions. Here, I only create one .vue file for login and registration, in which v-if is used to determine whether the login block and registration block elements are rendered, thereby affecting their display.
Initial setup
v-if="loginShow"为true, v-if="registerShow"为false
When the button is clicked to toggle, true and false are switched.
After successful registration, switch back to the login section.
For the sake of convenience and user habits, although the user attributes include id, username, password, phone, and gender, only the username and password are filled in during registration, and the function is simply implemented. The password is not encrypted, which is not safe enough. The article may be updated later to write about safer login and registration methods, as well as how to complete personal information after login.
LoginAndRegister.vue:
- <template>
- <div class="container">
- <div class="login-box" v-if="loginShow">
- <!-- 菱形群-->
- <div class="decoration1 decoration"></div>
- <div class="decoration2 decoration"></div>
- <div class="decoration3 decoration"></div>
- <div class="decoration4 decoration"></div>
- <div class="decoration5 decoration"></div>
- <div class="decoration decoration4 decoration6"></div>
- <div class="decoration decoration7 decoration2"></div>
- <div class="decoration decoration8 decoration3"></div>
- <div class="login-title">
- <h1>Login</h1>
- </div>
- <div class="login-part">
- <input class="login-input" v-model="username" placeholder="Username" />
- <input class="login-input" type="password" v-model="password" placeholder="Password" />
- <button class="login-button" @click="login">Login</button>
- <div>
- 还未注册?点击<a class="change-link" @click="changeToRegister">这里</a>注册
- </div>
- </div>
- </div>
- <div class="login-box" v-if="registerShow">
- <!-- 菱形群-->
- <div class="decoration1 decoration"></div>
- <div class="decoration2 decoration"></div>
- <div class="decoration3 decoration"></div>
- <div class="decoration4 decoration"></div>
- <div class="decoration5 decoration"></div>
- <div class="decoration decoration4 decoration6"></div>
- <div class="decoration decoration7 decoration2"></div>
- <div class="decoration decoration8 decoration3"></div>
- <div class="login-title">
- <h1>Register</h1>
- </div>
- <div class="login-part">
- <input class="login-input" v-model="username" placeholder="Username" />
- <input class="login-input" type="password" v-model="password" placeholder="Password" />
- <button class="login-button" @click="register">Register</button>
- <span class="change-link" @click="changeToLogin">返回登录</span>
- </div>
- </div>
- <!-- <div class="decoration decoration1"></div>-->
- <!-- <div class="decoration decoration2"></div>-->
- <!-- <div class="decoration decoration3"></div>-->
- <!-- <div class="decoration decoration4"></div>-->
- </div>
- </template>
-
- <script>
- import { ref } from 'vue'
- import { useRouter } from 'vue-router' // 导入 useRouter
-
- import '../style/Login.css' // 导入css
- export default {
- name: 'LoginVue',
- setup () {
- const username = ref('')
- const password = ref('')
- const phone = ref('')
- const loginShow = ref(true)
- const registerShow = ref(false)
- const router = useRouter()
-
- const changeToRegister = async () => {
- loginShow.value = false
- registerShow.value = true
- }
-
- const changeToLogin = async () => {
- loginShow.value = true
- registerShow.value = false
- }
-
- const login = async () => {
- console.log('Login with:', username.value, password.value)
- try {
- const formData = new FormData()
- formData.append('username', username.value)
- formData.append('password', password.value)
- const response = await fetch('http://localhost:8081/api/user/login', {
- method: 'POST',
- body: formData
- })
- const data = await response.json()
- if (response.ok) {
- console.log('Link success', data)
- if (data.code === 200) {
- // 登录成功
- alert('登录成功!')
- await router.push('/home')
- } else {
- alert(data.msg)
- }
- } else {
- console.error('Link failed', data)
- }
- } catch (error) {
- console.error('Error login', error)
- }
- }
-
- const register = async () => {
- console.log('Register with:', username.value, password.value)
- try {
- const formData = new FormData()
- formData.append('username', username.value)
- formData.append('password', password.value)
- const response = await fetch('http://localhost:8081/api/user/register', {
- method: 'POST',
- body: formData
- })
- const data = await response.json()
- if (response.ok) {
- if (data.code === 200) {
- console.log('Register success', data)
- alert('注册成功!')
- await changeToLogin()
- } else {
- console.log('Register failed', data)
- alert(data.msg)
- }
- } else {
- console.error('Register failed', data)
- }
- } catch (error) {
- console.error('Error during register', error)
- }
- }
-
- return { username, password, phone, login, loginShow, registerShow, changeToRegister, register, changeToLogin }
- }
- }
- </script>
-
- <style>
-
- </style>
Home.vue is the main page that jumps to after successful login.
Home.vue:
- <template>
- 首页<br><br>
- <button class="login-button" @click="signOut">退出登录</button>
- </template>
-
- <script>
- import { useRouter } from 'vue-router'
-
- export default {
- name: 'HomeVue',
- setup () {
- const router = useRouter()
- const signOut = async () => {
- await router.push('/')
- }
- return { signOut }
- }
- }
- </script>
-
- <style scoped>
-
- </style>
Page routing configuration, when the path is /, it redirects to the login page, /login is the login page, and /home is the home page.
index.js:
- import { createRouter, createWebHistory } from 'vue-router'
- import Login from '../components/LoginAndRegister.vue'
- import Home from '../views/Home.vue'
-
- const routes = [
- {
- path: '/',
- redirect: '/login'
- },
- {
- path: '/login',
- name: 'Login',
- component: Login
- },
- {
- path: '/home',
- name: 'Home',
- component: Home
- }
- ]
-
- const router = createRouter({
- history: createWebHistory(process.env.BASE_URL),
- routes
- })
-
- export default router
CSS design for the login and registration page.
Login.css:
- *{
- margin: 0;
- padding: 0;
- }
- .container{
- height: 100vh;
- display: flex;
- justify-content: center;
- align-items: center;
- overflow: hidden;
- position: relative;
- }
- .login-box{
- background-color: white;
- padding: 40px 100px;
- border-radius: 8px;
- box-shadow: 0 0 5px 1px gainsboro;
- position: relative;
- }
- .login-part{
- display: flex;
- flex-direction: column;
- justify-content: center;
- margin-top: 20px;
- gap: 20px;
- }
- .login-input{
- width: 250px;
- height: 30px;
- border-radius: 8px;
- }
- .login-button{
- height: 40px;
- border-radius: 8px;
- background-color: #2c3e50;
- color: white;
- transition: 0.5s;
- }
- .login-button:hover{
- background-color: darkcyan;
- font-size: 15px;
- transition: 0.5s;
- }
- .login-button:active{
- background-color: darkslateblue;
- }
- .change-link{
- color: #00BFFF;
- text-decoration: underline;
- }
- .change-link:hover{
- color: cornflowerblue;
- }
-
- .decoration {
- position: absolute;
- width: 200px;
- height: 200px;
- background: linear-gradient(to left, #FDF5E6, #96CDCD );
- clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
- z-index: 1;
- }
- .decoration1 {
- top: 150px;
- left: -210px;
- }
- .decoration2 {
- top: 20px;
- right: -20px;
- width: 100px; /* 第二个菱形的大小 */
- height: 100px;
- background: linear-gradient(to right, #FFF5EE, #E6E6FA);
- }
- .decoration3 {
- top: 50px;
- right: -180px;
- width: 200px; /* 第三个菱形的大小 */
- height: 200px;
- background: linear-gradient(to right, #7FFFD4, cadetblue);
- }
- .decoration4 {
- top: 200px;
- right: -200px;
- width: 500px; /* 第三个菱形的大小 */
- height: 500px;
- z-index: -1;
- clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
- background: linear-gradient(to right, #FFFACD, #00BFFF);
- }
- .decoration5 {
- top: -100px;
- right: 200px;
- width: 400px; /* 第三个菱形的大小 */
- height: 400px;
- z-index: -1;
- clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
- background: linear-gradient(to right, #AFEEEE, #00BFFF);
- }
- .decoration6 {
- top: 10px;
- right: -680px;
- }
-
- .decoration7 {
- top: -170px;
- right: -500px;
- }
-
- .decoration8 {
- top: -140px;
- right: -655px;
- }
The diamond blocks are randomly arranged, and at the beginning they look like this:
Later, I added a few more diamond blocks and changed their positions and colors. The final effect is as follows:
Use springboot, mysql, mybatis to simply build a backend project and connect to the database, refer to:
Supplement to the article:
If you find it troublesome to write set and get methods every time you create an entity class, you can add the following dependencies to pom.xml:
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- </dependency>
Then use @Data annotation in the entity class to omit the set and get methods:
The process is similar, but the data I created this time is a little different, mainly the user table attributes and data have changed (the difference is not big, the medicine is the same):
Problem encountered: Maven keeps downloading dependencies and does not respond for a long time
However, there were still some problems in the process of creating the project. This time I used a new computer to create the backend project. It was the first time to build it. As a result, after Maven started, it kept downloading various dependencies and plug-ins, and there was no response for a long time:
Solution:
Clear the cache and restart idea, but it has little effect.
Later I found that it might be because Maven used the foreign central warehouse by default, and I used the Maven plug-in in idea, so the download speed would be very slow.
So I downloaded Maven locally, refer to the tutorial:
Maven download and installation tutorial (super detailed)_maven installation-CSDN blog
Download according to the tutorial, modify the mirror URL in Maven installation path->conf->settings.xml, but I did not configure the environment variables, directly in the idea file->settings->Build,Execution,Deployment->Build Tools->Maven, change the Maven home path to the local path:
After the change, the download speed is much faster.
The final backend project directory structure is as follows:
Get the filled-in information passed by the front end, including the user name and password, and query the database based on the user name and password. If the user is found, it means that the user exists and the user name and password correspond, and the login is successful, otherwise it fails.
Get the filled-in information passed by the front end, including the user name and password. After determining that the input information is not empty, first search the user in the database according to the user name. If found, that is, the user name already exists, the registration fails and the failure information is returned. If the user is not found, you can register and insert the record into the database. After successful registration, display the login block and hide the registration block.
Where resources->mapper->UserMapper.xml:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
-
- <mapper namespace="com.example.demo.mapper.UserMapper" >
- <resultMap id="result" type="com.example.demo.entity.User">
- <result property="id" column="id" />
- <result property="username" column="username" />
- <result property="password" column="password" />
- <result property="phone" column="phone" />
- <result property="gender" column="gender"/>
- </resultMap>
-
- <!-- 通过用户名和密码查找对应用户,用于登录-->
- <select id="findUserByNameAndPwd" resultMap="result" parameterType="User">
- select * from user
- where username = #{username}
- and password = #{password}
- </select>
-
-
- <!-- 通过用户名查找对应用户,用于注册检验用户名是否已存在-->
- <select id="findUserByName" resultMap="result" parameterType="User">
- select * from user
- where username = #{username}
- </select>
-
- <!-- 添加用户-->
- <insert id="addUser" parameterType="User">
- insert into user (username, password)
- values ( #{username}, #{password} )
- </insert>
-
- </mapper>
java->com.example.demo->mapper->UserMapper.java:
- package com.example.demo.mapper;
-
- import com.example.demo.entity.User;
- import org.apache.ibatis.annotations.Mapper;
-
- @Mapper
- public interface UserMapper {
- // 通过用户名和密码查找对应用户
- public User findUserByNameAndPwd(User user);
- // 通过用户名查找用户
- public User findUserByName(User user);
- // 添加用户
- public void addUser(User user);
- }
java->com.example.demo->service->UserService.java:
- package com.example.demo.service;
-
- import com.example.demo.entity.User;
-
- public interface UserService {
- // 通过用户名和密码查找对应id
- public User findUserByNameAndPwd(User user);
- // 通过用户名查找用户
- public User findUserByName(User user);
- // 添加用户
- public void addUser(User user);
- }
java->com.example.demo->service->UserServiceImpl.java:
- package com.example.demo.service;
-
- import com.example.demo.entity.User;
- import com.example.demo.mapper.UserMapper;
- import jakarta.annotation.Resource;
- import org.springframework.stereotype.Service;
-
- @Service
- public class UserServiceImpl implements UserService {
- @Resource
- private UserMapper userMapper;
-
- // 通过用户名和密码查找对应id
- @Resource
- public User findUserByNameAndPwd(User user){
- return userMapper.findUserByNameAndPwd(user);
- }
-
- // 通过用户名查找用户
- @Resource
- public User findUserByName(User user){
- return userMapper.findUserByName(user);
- }
-
- // 添加用户
- @Resource
- public void addUser(User user){
- userMapper.addUser(user);
- }
- }
java->com.example.demo->controller->UserController.java:
- package com.example.demo.controller;
-
-
- import com.example.demo.entity.User;
- import com.example.demo.result.Result;
- import com.example.demo.service.UserService;
- import jakarta.annotation.Resource;
- import org.springframework.web.bind.annotation.*;
-
-
- @RestController
- @RequestMapping("/api/user")
- public class UserController {
- @Resource
- UserService userService;
-
- // 登录
- @CrossOrigin
- @PostMapping(value = "/login")
- public Result login(@ModelAttribute("user") User user){
- String username=user.getUsername();
- String password=user.getPassword();
- System.out.println("Login received username: " + username);
- System.out.println("Login received password: " + password);
- User userCheck = new User();
- userCheck.setUsername(username);
- userCheck.setPassword(password);
- System.out.println(userCheck.getUsername() + " " + userCheck.getPassword());
- try{
- User findUser = userService.findUserByNameAndPwd(userCheck);
- if(findUser != null){
- return Result.success(findUser);
- }else {
- return Result.failure(401,"用户名或密码错误");
- }
- }catch (Exception e){
- return Result.failure(500,"服务器异常");
- }
- }
-
- // 注册
- @CrossOrigin
- @PostMapping(value = "/register")
- public Result register(@ModelAttribute("user") User user){
- // String username = "222";
- // String password = "222";
- User userCheck = new User();
- userCheck.setUsername(user.getUsername());
- userCheck.setPassword(user.getPassword());
- if(userCheck.getUsername() == null || userCheck.getUsername().isEmpty() || userCheck.getPassword() == null || userCheck.getPassword().isEmpty()){
- System.out.println("用户名或密码不可为空");
- return Result.failure(201,"用户名和密码不可为空");
- }else {
- System.out.println("Register received username: " + userCheck.getUsername());
- System.out.println("Register received password: " + userCheck.getPassword());
- try{
- // 先在数据库中查找是否已有用户名相同的用户
- User findUser = userService.findUserByName(userCheck);
- if(findUser != null){
- // 用户名已存在
- return Result.failure(202,"用户名已存在!");
- }
- else {
- // 新用户,数据库添加记录
- userService.addUser(userCheck);
- return Result.success(userCheck);
- }
- }catch (Exception e) {
- return Result.failure(500, "服务器异常");
- // }
- }
- }
- }
- }
The front-end and back-end are started separately. Here I changed the back-end port to 8081 in application.properties, and the front-end is the default 8080. So after the front-end and back-end projects are successfully running, enter http://localhost:8080 in the browser. Check in the network of the developer tool that it is successfully connected to the back-end, and when logging in and registering for test input, it can successfully return different prompt information and pop-up prompts:
After successful login: