要实现一个使用 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 Boot、Vue.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. 运行步骤
- 启动 MySQL 数据库,确保数据库和表已创建。
- 启动 Spring Boot 后端。
- 启动 Vue.js 前端:
npm run serve
- 打开浏览器访问
http://localhost:8081
,输入用户名和密码进行登录。
5. 测试
- 输入正确的用户名和密码(如
admin
和123456
),页面显示“登录成功”。 - 输入错误的用户名或密码,页面显示“用户名或密码错误”。