CRUD (CREATE,READ,UPDATE,DELETE)operation spring program to find student by id with get and post request
public class Student {
private int id;
private String name;
private String email;
// getters and setters
}
@RestController
@RequestMapping("/students")
public class StudentController {
private Map<Integer, Student> students = new HashMap<>(); // a collection to store students
// POST request to add a new student
@PostMapping("/add")
public ResponseEntity<Student> addStudent(@RequestBody Student student) {
students.put(student.getId(), student);
return ResponseEntity.ok(student);
}
// GET request to find a student by ID
@GetMapping("/{id}")
public ResponseEntity<Student> getStudentById(@PathVariable int id) {
if (students.containsKey(id)) {
return ResponseEntity.ok(students.get(id));
}
return ResponseEntity.notFound().build();
}
}
The getStudentById method handles a GET request to find a student by their ID. It takes in the id of the student in the path variable, checks if the students collection contains a student with that ID, and returns the student object with an HTTP status code of 200 (OK) if found, or a 404 (Not Found) status code if not found.
@SpringBootApplication
public class StudentApplication {
public static void main(String[] args) {
SpringApplication.run(StudentApplication.class, args);
}
}
Thatβs it! You can now run the application and test it out using a REST client or a web browser. Here are a few sample requests:
{ βidβ: 1, βnameβ: βJohn Doeβ, βemailβ: βjohndoe@example.comβ }
* To find a student by ID:
``` java
GET http://localhost:8080/students/1
{
"id": 1,
"name": "John Doe",
"email": "johndoe@example.com"
}