添加一个查看所有用户的功能前后端代码Java语言
时间: 2024-03-03 21:49:44 浏览: 207
开源博客Java项目,前后端不分离
以下是Java语言的查看所有用户的前后端代码示例:
后端代码(使用Spring Boot框架):
1. UserController.java
```java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
}
```
2. UserService.java
```java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> getAllUsers() {
return userRepository.findAll();
}
}
```
3. UserRepository.java
```java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
```
前端代码(使用React框架):
1. UserList.js
```jsx
import React, { useState, useEffect } from "react";
import axios from "axios";
function UserList() {
const [users, setUsers] = useState([]);
useEffect(() => {
axios
.get("/users")
.then((response) => setUsers(response.data))
.catch((error) => console.log(error));
}, []);
return (
<div>
<h1>All Users</h1>
<ul>
{users.map((user) => (
<li key={user.id}>
{user.firstName} {user.lastName}
</li>
))}
</ul>
</div>
);
}
export default UserList;
```
2. App.js
```jsx
import React from "react";
import UserList from "./UserList";
function App() {
return (
<div>
<UserList />
</div>
);
}
export default App;
```
以上示例中,后端使用Spring Boot框架提供RESTful API,前端使用React框架调用后端API并展示用户列表。在浏览器中访问前端页面即可查看所有用户。
阅读全文