SpringBoot+Vue+JPA实现登录功能(代码+思路)

要实现一个使用 Vue.js 作为前端,Spring Boot 、Spring Data JPA作为后端的登录功能页面,并实现前后端交互,你可以按照以下步骤进行:

创建 Spring Boot 后端
创建 Spring Boot 项目

使用 Spring Initializr 创建一个新的 Spring Boot 项目,添加以下依赖:

  • Spring Web
  • Spring Data JPA
  • Spring Security
  • MySQL Driver (或其他数据库驱动)

以下是使用 Spring BootVue.js 和 MySQL 实现登录功能的完整代码,包含详细的中文注释。 

1. 后端实现(Spring Boot)

1.1 项目结构

src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           ├── controller
│   │           │   └── LoginController.java
│   │           ├── entity
│   │           │   └── User.java
│   │           ├── repository
│   │           │   └── UserRepository.java
│   │           ├── service
│   │           │   └── UserService.java
│   │           └── SpringBootLoginApplication.java
│   └── resources
│       └── application.properties
 

1.2 代码实现
1.2.1 User.java(用户实体类)
package com.example.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity // 标记为 JPA 实体
public class User {
    @Id // 主键
    @GeneratedValue(strategy = GenerationType.IDENTITY) // 自增主键
    private Long id;
    private String username; // 用户名
    private String password; // 密码

    // Getter 和 Setter 方法
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
1.2.2 UserRepository.java(用户仓库接口) 
package com.example.repository;

import com.example.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
    // 根据用户名查找用户
    User findByUsername(String username);
}
 1.2.3 UserService.java(用户服务类)

package com.example.service;

import com.example.entity.User;
import com.example.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service // 标记为 Spring 服务类
public class UserService {

    @Autowired // 自动注入 UserRepository
    private UserRepository userRepository;

    // 根据用户名查找用户
    public User findByUsername(String username) {
        return userRepository.findByUsername(username);
    }

    // 验证用户登录
    public boolean validateUser(String username, String password) {
        User user = findByUsername(username);
        if (user != null && user.getPassword().equals(password)) {
            return true; // 用户名和密码匹配
        }
        return false; // 用户名或密码错误
    }
}
1.2.4 LoginController.java(登录控制器) 
package com.example.controller;

import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController // 标记为 REST 控制器
@RequestMapping("/api") // 基础路径
public class LoginController {

    @Autowired // 自动注入 UserService
    private UserService userService;

    @PostMapping("/login") // 处理登录请求
    public String login(@RequestParam String username, @RequestParam String password) {
        if (userService.validateUser(username, password)) {
            return "登录成功";
        } else {
            return "用户名或密码错误";
        }
    }
}
1.2.5 application.properties(配置文件)
# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update

# 服务器端口
server.port=8080
1.2.6 SpringBootLoginApplication.java(启动类)
package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication // 标记为 Spring Boot 应用
public class SpringBootLoginApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootLoginApplication.class, args);
    }
}

2. 前端实现(Vue.js)

2.1 项目结构

src
├── components
│   └── Login.vue
├── App.vue
├── main.js

2.2 代码实现
2.2.1 Login.vue(登录组件)
<template>
  <div>
    <h2>登录</h2>
    <form @submit.prevent="login">
      <div>
        <label for="username">用户名:</label>
        <input type="text" id="username" v-model="username" required />
      </div>
      <div>
        <label for="password">密码:</label>
        <input type="password" id="password" v-model="password" required />
      </div>
      <button type="submit">登录</button>
    </form>
    <p>{{ message }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '', // 用户名
      password: '', // 密码
      message: '' // 登录结果消息
    };
  },
  methods: {
    async login() {
      try {
        // 发送登录请求
        const response = await this.$http.post('/api/login', null, {
          params: {
            username: this.username,
            password: this.password
          }
        });
        this.message = response.data; // 显示登录结果
      } catch (error) {
        this.message = '登录失败: ' + error.response.data; // 显示错误信息
      }
    }
  }
};
</script>
2.2.2 App.vue(主组件)
<template>
  <div id="app">
    <Login />
  </div>
</template>

<script>
import Login from './components/Login.vue';

export default {
  components: {
    Login
  }
};
</script>
2.2.3 main.js(入口文件)
import Vue from 'vue';
import App from './App.vue';
import axios from 'axios';

Vue.config.productionTip = false;

// 配置 Axios
Vue.prototype.$http = axios.create({
  baseURL: 'http://localhost:8080', // 后端地址
  headers: {
    'Content-Type': 'application/json'
  }
});

new Vue({
  render: h => h(App),
}).$mount('#app');

3. 数据库配置(MySQL)

3.1 创建数据库和表
CREATE DATABASE mydatabase;

USE mydatabase;

CREATE TABLE user (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    password VARCHAR(50) NOT NULL
);

-- 插入测试用户
INSERT INTO user (username, password) VALUES ('admin', '123456');

4. 运行步骤

  1. 启动 MySQL 数据库,确保数据库和表已创建。
  2. 启动 Spring Boot 后端。
  3. 启动 Vue.js 前端:
    npm run serve
    
    • 打开浏览器访问 http://localhost:8081,输入用户名和密码进行登录。

    5. 测试

    • 输入正确的用户名和密码(如 admin 和 123456),页面显示“登录成功”。
    • 输入错误的用户名或密码,页面显示“用户名或密码错误”。
    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包

    打赏作者

    @百思不得奇解

    你的鼓励将是我创作的最大动力

    ¥1 ¥2 ¥4 ¥6 ¥10 ¥20
    扫码支付:¥1
    获取中
    扫码支付

    您的余额不足,请更换扫码支付或充值

    打赏作者

    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值