后端 Java 接口实现
-
首先,确保你已经配置好数据库连接信息,并且已经创建了相应的数据库表。
-
创建一个实体类
User
来表示用户信息:
-
// User.java public class User {private Long id;private String username;private String email;// 省略 getter 和 setter 方法 }
- 创建一个
UserRepository
接口来定义数据库操作方法:// UserRepository.java public interface UserRepository {List<User> getAllUsers();User getUserById(Long id);void createUser(User user);void updateUser(User user);void deleteUser(Long id); }
- 创建一个
UserRepositoryImpl
类来实现UserRepository
接口,完成数据库操作:// UserRepositoryImpl.java @Repository public class UserRepositoryImpl implements UserRepository {@Autowiredprivate JdbcTemplate jdbcTemplate;@Overridepublic List<User> getAllUsers() {String sql = "SELECT * FROM users";return jdbcTemplate.query(sql, BeanPropertyRowMapper.newInstance(User.class));}@Overridepublic User getUserById(Long id) {String sql = "SELECT * FROM users WHERE id = ?";return jdbcTemplate.queryForObject(sql, new Object[]{id}, BeanPropertyRowMapper.newInstance(User.class));}@Overridepublic void createUser(User user) {String sql = "INSERT INTO users (username, email) VALUES (?, ?)";jdbcTemplate.update(sql, user.getUsername(), user.getEmail());}@Overridepublic void updateUser(User user) {String sql = "UPDATE users SET username = ?, email = ? WHERE id = ?";jdbcTemplate.update(sql, user.getUsername(), user.getEmail(), user.getId());}@Overridepublic void deleteUser(Long id) {String sql = "DELETE FROM users WHERE id = ?";jdbcTemplate.update(sql, id);} }
- 创建一个
UserController
类来处理前端请求并调用数据库操作:// UserController.java @RestController @RequestMapping("/api/users") public class UserController {@Autowiredprivate UserRepository userRepository;@GetMapping("/")public List<User> getAllUsers() {return userRepository.getAllUsers();}@GetMapping("/{id}")public User getUserById(@PathVariable Long id) {return userRepository.getUserById(id);}@PostMapping("/")public void createUser(@RequestBody User user) {userRepository.createUser(user);}@PutMapping("/")public void updateUser(@RequestBody User user) {userRepository.updateUser(user);}@DeleteMapping("/{id}")public void deleteUser(@PathVariable Long id) {userRepository.deleteUser(id);} }
前端调用示例
在前端部分,你可以使用 Axios 或其他 HTTP 请求库来调用后端接口。以下是一个简单的示例:
// 假设使用 Axios 库发送 HTTP 请求 axios.get('/api/users').then(response => {// 处理获取用户列表的响应数据console.log(response.data);}).catch(error => {// 处理错误console.error(error);});// 创建用户 const newUser = { username: 'john_doe', email: 'john@example.com' }; axios.post('/api/users', newUser).then(response => {// 处理创建用户的响应console.log('User created successfully');}).catch(error => {// 处理错误console.error(error);});// 更新用户 const updatedUser = { id: 1, username: 'updated_username', email: 'updated_email@example.com' }; axios.put('/api/users', updatedUser).then(response => {// 处理更新用户的响应console.log('User updated successfully');}).catch(error => {// 处理错误console.error(error);});// 删除用户 const userId = 1; axios.delete(`/api/users/${userId}`).then(response => {// 处理删除用户的响应console.log('User deleted successfully');}).catch(error => {// 处理错误console.error(error);});