Added reading data from database using springboot
This commit is contained in:
66
src/main/java/ch/progetto152/controller/UserController.java
Normal file
66
src/main/java/ch/progetto152/controller/UserController.java
Normal file
@@ -0,0 +1,66 @@
|
||||
package ch.progetto152.controller;
|
||||
|
||||
|
||||
import ch.progetto152.entity.User;
|
||||
import ch.progetto152.services.UserService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/users")
|
||||
public class UserController {
|
||||
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
@Autowired
|
||||
public UserController(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@GetMapping("/get/all")
|
||||
public ResponseEntity<List<User>> getAllUsers() {
|
||||
List<User> users = userService.getAllUsers();
|
||||
return new ResponseEntity<>(users, HttpStatus.OK);
|
||||
}
|
||||
|
||||
@GetMapping("/get/{id}")
|
||||
public ResponseEntity<User> getUserById(@PathVariable("id") Long id) {
|
||||
User user = userService.getUserByIdService(id);
|
||||
if (user != null) {
|
||||
return new ResponseEntity<>(user, HttpStatus.OK);
|
||||
} else {
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/create/{id}")
|
||||
public ResponseEntity<User> createUser(@RequestBody User user) {
|
||||
User createdUser = userService.createUser(user);
|
||||
return new ResponseEntity<>(createdUser, HttpStatus.CREATED);
|
||||
}
|
||||
|
||||
@PutMapping("/put/{id}")
|
||||
public ResponseEntity<User> updateUser(@PathVariable("id") Long id, @RequestBody User user) {
|
||||
User updatedUser = userService.updateUser(id, user);
|
||||
if (updatedUser != null) {
|
||||
return new ResponseEntity<>(updatedUser, HttpStatus.OK);
|
||||
} else {
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
@DeleteMapping("/delete/{id}")
|
||||
public ResponseEntity<Void> deleteUser(@PathVariable("id") Long id) {
|
||||
boolean deleted = userService.deleteUser(id);
|
||||
if (deleted) {
|
||||
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
||||
} else {
|
||||
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user