面试题答案
一键面试在Spring Boot中,可以通过@RequestMapping
注解及其衍生注解来处理不同的HTTP请求方法,实现对资源的增删改查操作。以下是具体的代码示例:
-
创建Spring Boot项目: 可以通过Spring Initializr(https://start.spring.io/)快速创建一个Spring Boot项目,选择合适的依赖,如Spring Web。
-
定义实体类: 假设我们有一个
User
实体类,用于表示用户资源。public class User { private Long id; private String name; private String email; // 构造函数、Getter和Setter方法 public User() { } public User(Long id, String name, String email) { this.id = id; this.name = name; this.email = email; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
-
创建控制器: 在控制器中处理不同的HTTP请求方法。
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicLong; @RestController @RequestMapping("/users") public class UserController { private static final AtomicLong counter = new AtomicLong(); private static final List<User> users = new ArrayList<>(); // GET请求,获取所有用户 @GetMapping public List<User> getAllUsers() { return users; } // GET请求,根据ID获取单个用户 @GetMapping("/{id}") public ResponseEntity<User> getUserById(@PathVariable Long id) { User user = users.stream() .filter(u -> u.getId().equals(id)) .findFirst() .orElse(null); if (user == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } return new ResponseEntity<>(user, HttpStatus.OK); } // POST请求,创建新用户 @PostMapping public ResponseEntity<User> createUser(@RequestBody User user) { user.setId(counter.incrementAndGet()); users.add(user); return new ResponseEntity<>(user, HttpStatus.CREATED); } // PUT请求,更新用户 @PutMapping("/{id}") public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User userDetails) { User user = users.stream() .filter(u -> u.getId().equals(id)) .findFirst() .orElse(null); if (user == null) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } user.setName(userDetails.getName()); user.setEmail(userDetails.getEmail()); return new ResponseEntity<>(user, HttpStatus.OK); } // DELETE请求,删除用户 @DeleteMapping("/{id}") public ResponseEntity<HttpStatus> deleteUser(@PathVariable Long id) { boolean deleted = users.removeIf(u -> u.getId().equals(id)); if (deleted) { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } else { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } }
在上述代码中:
@GetMapping
处理GET请求,分别实现了获取所有用户和根据ID获取单个用户的功能。@PostMapping
处理POST请求,用于创建新用户,@RequestBody
用于将请求体中的JSON数据绑定到User
对象。@PutMapping
处理PUT请求,用于更新用户信息。@DeleteMapping
处理DELETE请求,用于删除指定ID的用户。
通过这些注解和方法,可以方便地在Spring Boot中实现RESTful API的增删改查操作。