springboot vue前后端分离登陆注册
时间: 2025-01-04 14:36:12 浏览: 12
### 关于Spring Boot 和 Vue.js 实现前后端分离的登录注册功能
#### 后端部分 (Spring Boot)
为了创建一个安全可靠的用户认证系统,在后端需要设置几个关键组件:
- **User实体类**: 定义用户的属性,如用户名、密码等。
```java
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
// Getters and Setters...
}
```
- **Repository接口**: 提供对数据库的操作方法。这通常继承自`JpaRepository`[^2]。
```java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
}
```
- **Service服务层**: 处理业务逻辑,比如验证用户输入并调用存储库保存新用户或查找现有用户。
```java
@Service
public class UserService {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private UserRepository userRepository;
public void register(User user){
user.setPassword(passwordEncoder.encode(user.getPassword()));
userRepository.save(user);
}
public boolean authenticate(String username, String rawPassword) {
var optUser = userRepository.findByUsername(username);
if(optUser.isEmpty()) return false;
return passwordEncoder.matches(rawPassword,optUser.get().getPassword());
}
}
```
- **Controller控制器层**: 接收HTTP请求并将它们转发给适当的服务进行处理;返回JSON响应给客户端。
```java
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private UserService userService;
@PostMapping("/register")
public ResponseEntity<String> register(@RequestBody User newUser){
try{
userService.register(newUser);
return new ResponseEntity<>("Registration successful", HttpStatus.CREATED);
}catch(Exception e){
return new ResponseEntity<>(e.getMessage(),HttpStatus.BAD_REQUEST);
}
}
@PostMapping("/login")
public ResponseEntity<Map<String,Object>> login(@RequestBody Map<String,String> credentials){
final String username = credentials.get("username");
final String password = credentials.get("password");
if(!userService.authenticate(username,password)){
throw new BadCredentialsException("Invalid Credentials!");
}
// Generate JWT token here...
HashMap<String,Object> response = new HashMap<>();
response.put("message","Login Successful");
// Add the generated JWT to this map as well.
return new ResponseEntity<>(response,HttpStatus.OK);
}
}
```
以上代码片段展示了如何构建基本的身份验证API,其中包含了用户注册和登录的功能。
#### 前端部分 (Vue.js)
对于前端而言,则需利用Axios发送异步HTTP请求到上述定义好的RESTful API,并根据服务器反馈更新视图状态。
##### 用户注册页面 (`Register.vue`)
此文件负责收集表单数据并通过POST请求提交至后端API完成账户创建过程。
```html
<template>
<div>
<!-- Form elements -->
<form v-on:submit.prevent="handleRegister">
<input type="text" placeholder="Enter your name..." required v-model.trim="newUser.username"/>
<input type="password" placeholder="Create a strong password..." required v-model.trim="newUser.password"/>
<button type="submit">Sign Up</button>
</form>
{{ message }}
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import axios from "axios";
export default defineComponent({
data() {
return {
newUser: {},
message: ''
};
},
methods:{
handleRegister(){
const path = `http://localhost:8080/api/auth/register`;
axios.post(path,this.newUser).then((res)=>{
console.log(res.data.message);
alert('Account created successfully!');
// Redirect logic can be added here.
}).catch(err=>{
console.error(`Error occurred during registration ${err}`);
this.message= err.response?.data || "An unexpected error has happened.";
});
}
}
});
</script>
```
##### 用户登录页面 (`Login.vue`)
该模板用于接收来自用户的凭证信息并向后端发起身份验证请求。
```html
<template>
<div>
<!-- Login form goes here -->
<form v-on:submit.prevent="handleSubmit">
<input type="email" placeholder="Email address.." required v-model.trim="credentials.email"/>
<input type="password" placeholder="Your secret key.." required v-model.trim="credentials.password"/>
<button>Login Now!</button>
</form>
{{ errorMessage }}
<router-link :to="{name:'home'}">Back Home</router-link>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import router from '../router/index';
const credentials = ref({});
let errorMessage = '';
function handleSubmit(){
fetch('/api/auth/login',{
method:"POST",
headers:{'Content-Type':'application/json'},
body: JSON.stringify(credentials.value),
})
.then(response => {
if (!response.ok) throw Error('Failed Authentication');
localStorage.setItem('token', response.headers.get('Authorization'));
router.push({name:'dashboard'});
})
.catch(error=>errorMessage=`Authentication failed: ${error}`)
};
</script>
```
阅读全文