springboot vue前后端分离实例代码
时间: 2023-10-30 16:02:59 浏览: 53
这里提供一个简单的基于 Spring Boot 和 Vue.js 的前后端分离项目示例代码。
1. 后端代码
在 Spring Boot 中,我们可以使用 Spring Web 实现 RESTful API。
首先,在 pom.xml 中添加以下依赖:
```xml
<dependencies>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Spring Boot DevTools (optional) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
```
然后,创建一个基本的实体类和一个 JPA Repository:
```java
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String email;
// getters and setters
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
```
接着,创建一个 RESTful Controller:
```java
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("")
public List<User> getAllUsers() {
return userRepository.findAll();
}
@PostMapping("")
public User createUser(@RequestBody User user) {
return userRepository.save(user);
}
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
Optional<User> user = userRepository.findById(id);
return user.map(response -> ResponseEntity.ok().body(response))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
Optional<User> existingUser = userRepository.findById(id);
return existingUser.map(u -> {
u.setName(user.getName());
u.setEmail(user.getEmail());
User updatedUser = userRepository.save(u);
return ResponseEntity.ok().body(updatedUser);
}).orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteUser(@PathVariable Long id) {
return userRepository.findById(id).map(user -> {
userRepository.delete(user);
return ResponseEntity.ok().build();
}).orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
}
```
最后,创建一个 Spring Boot 应用程序类:
```java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
2. 前端代码
我们使用 Vue.js 和 axios 来实现前端应用程序。
首先,在 package.json 中添加以下依赖:
```json
"dependencies": {
"axios": "^0.19.0",
"vue": "^2.6.10",
"vue-router": "^3.0.3"
}
```
然后,创建一个 Vue 组件:
```html
<template>
<div>
<h1>Users</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr v-for="user in users" :key="user.id">
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
<td>
<button @click="editUser(user)">Edit</button>
<button @click="deleteUser(user.id)">Delete</button>
</td>
</tr>
</tbody>
</table>
<form>
<label>Name:</label>
<input type="text" v-model="user.name" />
<label>Email:</label>
<input type="email" v-model="user.email" />
<button type="submit" @click.prevent="saveUser()">Save</button>
</form>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
users: [],
user: { name: "", email: "" },
editing: false,
};
},
mounted() {
this.getUsers();
},
methods: {
getUsers() {
axios.get("/api/users").then((response) => {
this.users = response.data;
});
},
saveUser() {
if (this.editing) {
axios.put("/api/users/" + this.user.id, this.user).then((response) => {
this.getUsers();
this.user = { name: "", email: "" };
this.editing = false;
});
} else {
axios.post("/api/users", this.user).then((response) => {
this.getUsers();
this.user = { name: "", email: "" };
});
}
},
editUser(user) {
this.user = Object.assign({}, user);
this.editing = true;
},
deleteUser(id) {
axios.delete("/api/users/" + id).then((response) => {
this.getUsers();
});
},
},
};
</script>
```
最后,创建一个 Vue 应用程序类:
```html
<template>
<div>
<router-view></router-view>
</div>
</template>
<script>
import Users from "./components/Users.vue";
export default {
components: {
Users,
},
};
</script>
```
3. 运行示例
将前端部分代码放在一个名为 `frontend` 的文件夹中,后端部分代码放在一个名为 `backend` 的文件夹中。
在 `frontend` 文件夹中运行以下命令:
```bash
npm install
npm run build
```
然后将生成的 `dist` 文件夹复制到 `backend/src/main/resources/static` 文件夹中。
在 `backend` 文件夹中运行以下命令:
```bash
./mvnw spring-boot:run
```
现在,你可以访问 http://localhost:8080/ 查看示例应用程序。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)