الفصل 2: التعليقات التوضيحية للويب وREST
1. التعليقات التوضيحية للمتحكم
@RestController مقابل @Controller
// يعيد VUES (HTML)
@Controller
public class PageController {
@GetMapping("/home")
public String home() {
return "home"; // يبحث عن قالب home.html
}
}
// يعيد DONNÉES (JSON/XML)
@RestController
public class ApiController {
@GetMapping("/api/data")
public Map<String, String> getData() {
return Map.of("message", "Hello"); // يتم تسلسله إلى JSON تلقائيًا
}
}
@ResponseBody
يجبر على الإرجاع بصيغة JSON/XML (يستخدم مع @Controller).
@Controller
public class MixedController {
@GetMapping("/page")
public String page() {
return "page"; // يعيد عرض
}
@GetMapping("/api/info")
@ResponseBody
public Map<String, String> info() {
return Map.of("version", "1.0"); // يعيد JSON
}
}
2. التعليقات التوضيحية لتوجيه HTTP
@RequestMapping
تعليق توضيحي أساسي لتوجيه URL إلى طريقة. يمكن تحديد طريقة HTTP.
@RestController
@RequestMapping("/api/v1/products") // بادئة لجميع الطرق
public class ProductController {
@RequestMapping(method = RequestMethod.GET)
public List<Product> getAll() { ... }
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Product getById(@PathVariable Long id) { ... }
}
@GetMapping
اختصار لـ @RequestMapping(method = GET).
@GetMapping
public List<Product> getAll() {
return productService.findAll();
}
@GetMapping("/{id}")
public Product getById(@PathVariable Long id) {
return productService.findById(id);
}
@GetMapping("/search")
public List<Product> search(@RequestParam String name) {
return productService.findByName(name);
}
@PostMapping
اختصار لـ @RequestMapping(method = POST).
@PostMapping
public ResponseEntity<Product> create(@Valid @RequestBody ProductDto dto) {
Product created = productService.create(dto);
return ResponseEntity.status(HttpStatus.CREATED).body(created);
}
@PutMapping
اختصار لـ @RequestMapping(method = PUT). استبدال كامل لمورد.
@PutMapping("/{id}")
public Product update(@PathVariable Long id, @Valid @RequestBody ProductDto dto) {
return productService.update(id, dto);
}
@PatchMapping
اختصار لـ @RequestMapping(method = PATCH). تحديث جزئي لمورد.
@PatchMapping("/{id}")
public Product partialUpdate(@PathVariable Long id, @RequestBody Map<String, Object> updates) {
return productService.partialUpdate(id, updates);
}
@DeleteMapping
اختصار لـ @RequestMapping(method = DELETE).
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
productService.delete(id);
return ResponseEntity.noContent().build();
}
ملخص التوجيهات
| Annotation | طريقة HTTP | الاستخدام النموذجي |
|---|---|---|
@GetMapping | GET | قراءة البيانات |
@PostMapping | POST | إنشاء مورد |
@PutMapping | PUT | استبدال مورد |
@PatchMapping | PATCH | تعديل جزئي |
@DeleteMapping | DELETE | حذف مورد |
3. التعليقات التوضيحية للمعلمات
@PathVariable
يستخرج قيمة من URL.
// GET /api/users/42
@GetMapping("/api/users/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
// GET /api/users/42/orders/7
@GetMapping("/api/users/{userId}/orders/{orderId}")
public Order getOrder(@PathVariable Long userId, @PathVariable Long orderId) {
return orderService.findByUserAndId(userId, orderId);
}
// اسم مختلف عن معلمة URL
@GetMapping("/api/categories/{category-name}")
public Category getCategory(@PathVariable("category-name") String categoryName) {
return categoryService.findByName(categoryName);
}
@RequestParam
يستخرج معلمة من سلسلة الاستعلام.
// GET /api/products?category=electronics
@GetMapping("/api/products")
public List<Product> getByCategory(@RequestParam String category) {
return productService.findByCategory(category);
}
// معلمة اختيارية بقيمة افتراضية
// GET /api/products?page=0&size=20&sort=name
@GetMapping("/api/products")
public Page<Product> getAll(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size,
@RequestParam(defaultValue = "name") String sort) {
return productService.findAll(PageRequest.of(page, size, Sort.by(sort)));
}
// معلمة اختيارية بدون قيمة افتراضية
@GetMapping("/api/search")
public List<Product> search(
@RequestParam(required = false) String name,
@RequestParam(required = false) BigDecimal minPrice) {
return productService.search(name, minPrice);
}
@RequestBody
يفك تسلسل جسم الطلب (JSON → كائن Java).
@PostMapping("/api/users")
public User createUser(@RequestBody UserDto userDto) {
return userService.create(userDto);
}
// جسم الطلب (JSON)
{
"name": "Jean Dupont",
"email": "jean@example.com",
"password": "secret123"
}
@RequestHeader
يستخرج قيمة من رأس HTTP.
@GetMapping("/api/profile")
public User getProfile(@RequestHeader("Authorization") String authHeader) {
String token = authHeader.replace("Bearer ", "");
return userService.findByToken(token);
}
@GetMapping("/api/info")
public Map<String, String> info(
@RequestHeader("User-Agent") String userAgent,
@RequestHeader(value = "Accept-Language", defaultValue = "fr") String lang) {
return Map.of("userAgent", userAgent, "language", lang);
}
@CookieValue
يستخرج قيمة من ملف تعريف الارتباط.
@GetMapping("/api/preferences")
public Preferences getPrefs(@CookieValue(value = "theme", defaultValue = "light") String theme) {
return new Preferences(theme);
}
@ModelAttribute
يربط معلمات النموذج بكائن (يستخدم بشكل خاص مع @Controller).
@PostMapping("/register")
public String register(@ModelAttribute RegistrationForm form) {
userService.register(form);
return "redirect:/login";
}
4. التعليقات التوضيحية للاستجابة
@ResponseStatus
يحدد رمز HTTP للاستجابة.
@PostMapping
@ResponseStatus(HttpStatus.CREATED) // 201
public Product create(@RequestBody ProductDto dto) {
return productService.create(dto);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT) // 204
public void delete(@PathVariable Long id) {
productService.delete(id);
}
الاستخدام مع الاستثناءات:
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
5. التعليقات التوضيحية لإدارة الأخطاء
@ExceptionHandler
يدير الاستثناءات على مستوى المتحكم.
@RestController
public class UserController {
@GetMapping("/api/users/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id); // قد يطلق ResourceNotFoundException
}
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public Map<String, String> handleNotFound(ResourceNotFoundException ex) {
return Map.of("error", ex.getMessage());
}
}
@ControllerAdvice / @RestControllerAdvice
إدارة عامة للاستثناءات لجميع المتحكمات.
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorResponse handleNotFound(ResourceNotFoundException ex) {
return new ErrorResponse("NOT_FOUND", ex.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleValidation(MethodArgumentNotValidException ex) {
List<String> errors = ex.getBindingResult().getFieldErrors().stream()
.map(e -> e.getField() + ": " + e.getDefaultMessage())
.toList();
return new ErrorResponse("VALIDATION_ERROR", errors.toString());
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorResponse handleGeneral(Exception ex) {
return new ErrorResponse("INTERNAL_ERROR", "Une erreur est survenue");
}
}
6. التعليقات التوضيحية لـ CORS وغيرها
@CrossOrigin
يضبط مشاركة الموارد عبر الأصل (CORS).
@RestController
@CrossOrigin(origins = "http://localhost:3000")
public class ApiController {
// جميع الطرق تسمح بالطلبات من localhost:3000
}
@GetMapping("/api/public")
@CrossOrigin(origins = "*", maxAge = 3600)
public String publicEndpoint() {
return "accessible de partout";
}
7. التعليقات التوضيحية للتحقق
@Valid / @Validated
يفعل التحقق من البيانات المستلمة.
@PostMapping("/api/users")
public User create(@Valid @RequestBody CreateUserDto dto) {
return userService.create(dto);
}
public class CreateUserDto {
@NotNull(message = "Le nom est obligatoire")
@Size(min = 2, max = 50, message = "Le nom doit faire entre 2 et 50 caractères")
private String name;
@NotBlank(message = "L'email est obligatoire")
@Email(message = "Format d'email invalide")
private String email;
@NotNull
@Size(min = 8, message = "Le mot de passe doit faire au moins 8 caractères")
private String password;
@Min(value = 0, message = "L'âge doit être positif")
@Max(value = 150, message = "L'âge doit être inférieur à 150")
private Integer age;
@Pattern(regexp = "^\\+?[0-9]{10,15}$", message = "Numéro de téléphone invalide")
private String phone;
}
التعليقات التوضيحية المتاحة للتحقق
| Annotation | الوصف |
|---|---|
@NotNull | لا يمكن أن يكون null |
@NotEmpty | ليس null وليس فارغًا (String, Collection) |
@NotBlank | ليس null، ليس فارغًا، ليس فقط مسافات |
@Size(min, max) | الحجم بين min وmax |
@Min(value) | القيمة الدنيا (أرقام) |
@Max(value) | القيمة القصوى (أرقام) |
@Email | صيغة بريد إلكتروني صالحة |
@Pattern(regexp) | يطابق التعبير النمطي |
@Positive | عدد موجب تمامًا |
@PositiveOrZero | عدد موجب أو صفر |
@Negative | عدد سالب تمامًا |
@Past | تاريخ في الماضي |
@Future | تاريخ في المستقبل |
@DecimalMin | القيمة العشرية الدنيا |
@DecimalMax | القيمة العشرية القصوى |
ملخص سريع
| Annotation | الدور |
|---|---|
@RestController | متحكم REST (JSON) |
@RequestMapping | توجيه URL الأساسي |
@GetMapping | GET |
@PostMapping | POST |
@PutMapping | PUT |
@PatchMapping | PATCH |
@DeleteMapping | DELETE |
@PathVariable | معلمة في URL |
@RequestParam | معلمة سلسلة الاستعلام |
@RequestBody | جسم JSON → كائن |
@RequestHeader | رأس HTTP |
@ResponseStatus | رمز استجابة HTTP |
@ExceptionHandler | إدارة استثناء محلية |
@RestControllerAdvice | إدارة استثناء عامة |
@CrossOrigin | إعداد CORS |
@Valid | يفعل التحقق |
➡️ الفصل 3: التعليقات التوضيحية للبيانات وJPA