springboot+vue实现登录功能代码
时间: 2023-07-30 20:10:19 浏览: 67
以下是一个简单的示例代码,展示如何使用Spring Boot和Vue.js实现登录功能。
Spring Boot REST API:
```java
@RestController
public class AuthController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtUtil jwtUtil;
@PostMapping("/authenticate")
public ResponseEntity<?> authenticate(@RequestBody AuthRequest authRequest) throws Exception {
try {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(authRequest.getUsername(), authRequest.getPassword())
);
} catch (BadCredentialsException e) {
throw new Exception("Incorrect username or password", e);
}
final UserDetails userDetails = userDetailsService
.loadUserByUsername(authRequest.getUsername());
final String token = jwtUtil.generateToken(userDetails);
return ResponseEntity.ok(new AuthResponse(token));
}
}
```
AuthRequest和AuthResponse类:
```java
public class AuthRequest {
private String username;
private String password;
// getters and setters
}
public class AuthResponse {
private final String token;
public AuthResponse(String token) {
this.token = token;
}
public String getToken() {
return token;
}
}
```
Vue.js登录页面:
```html
<template>
<div>
<h1>Login</h1>
<div v-if="error" style="color: red">{{ error }}</div>
<div>
<input type="text" v-model="username" placeholder="Username">
</div>
<div>
<input type="password" v-model="password" placeholder="Password">
</div>
<div>
<button @click="login">Login</button>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
username: '',
password: '',
error: ''
};
},
methods: {
login() {
axios.post('/api/authenticate', {
username: this.username,
password: this.password
})
.then(response => {
localStorage.setItem('token', response.data.token);
this.$router.push('/');
})
.catch(error => {
this.error = error.response.data.message;
});
}
}
};
</script>
```
请注意,这只是一个简单的示例代码,并且缺少一些必要的组件,例如身份验证拦截器。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)