springboot+vue编写用户注册登录界面具体代码
时间: 2023-03-19 11:22:34 浏览: 268
为了编写用户注册登录界面,需要使用到前端框架Vue.js和后端框架Spring Boot。以下是一个简单的实现示例:
1. 创建一个Spring Boot项目并添加以下依赖项:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
```
2. 创建一个实体类User.java,该类表示用户并包含以下属性:
```
@Entity
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String username;
private String password;
// getters and setters
}
```
3. 创建一个Spring Boot控制器UserController.java,并编写以下方法:
```
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@PostMapping("/api/register")
public User register(@RequestBody User user) {
userRepository.save(user);
return user;
}
@PostMapping("/api/login")
public User login(@RequestBody User user) {
User savedUser = userRepository.findByUsername(user.getUsername());
if (savedUser != null && savedUser.getPassword().equals(user.getPassword())) {
return savedUser;
} else {
return null;
}
}
}
```
4. 创建一个Vue.js组件Login.vue,包含一个表单和两个按钮:
```
<template>
<form>
<input type="text" v-model="username" placeholder="Username">
<input type="password" v-model="password" placeholder="Password">
<button type="button" @click="login">Login</button>
<button type="button" @click="register">Register</button>
</form>
</template>
<script>
export default {
data() {
return {
username: '',
password: ''
}
},
methods: {
login() {
fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.username,
password: this.password
})
})
.then(response => response.json())
.then(data => {
// handle successful login
})
.catch(error => {
// handle login error
})
},
register() {
fetch('/api/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: this.username,
password: this.password
})
})
.then(response => response.json())
.then(data => {
// handle successful registration
})
.catch(error => {
// handle registration error
})
}
}
}
</script>
```
5. 将Login.vue组件添加到App.vue中:
```
<template>
<div>
<Login/>
</div>
</template>
<script>
import Login from './components/Login.vue';
export default {
components: {
Login
}
}
</script>
```
6. 运行Spring
阅读全文