-
Notifications
You must be signed in to change notification settings - Fork 0
5_Валидация, Интернационализация #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| package org.javaspringcourse.controller; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import org.javaspringcourse.dto.ArticleIn; | ||
| import org.javaspringcourse.service.ArticleService; | ||
| import org.springframework.http.HttpStatus; | ||
| import org.springframework.web.bind.annotation.*; | ||
|
|
||
| @RestController | ||
| @RequestMapping("/article") | ||
| @RequiredArgsConstructor | ||
| public class ArticleController { | ||
| private final ArticleService service; | ||
|
|
||
| @PostMapping("/create") | ||
| @ResponseStatus(HttpStatus.CREATED) | ||
| public String register(@RequestBody ArticleIn article) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Возвращать следует ДТО |
||
| return service.create(article); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| package org.javaspringcourse.dto; | ||
|
|
||
| import jakarta.validation.constraints.NotBlank; | ||
| import lombok.Data; | ||
| import org.javaspringcourse.validation.RussianFullName; | ||
| import org.javaspringcourse.validation.Title; | ||
|
|
||
| @Data | ||
| public class ArticleIn { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Начиная с java 17 для дто следует использовать record, когда это возможно. Или хотя бы использовать |
||
| @Title private String title; | ||
| @RussianFullName private String author; | ||
| @NotBlank private String content; | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return title + " (" + author + ")"; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| package org.javaspringcourse.exception; | ||
|
|
||
| import jakarta.validation.ConstraintViolation; | ||
| import jakarta.validation.ConstraintViolationException; | ||
| import org.springframework.http.HttpStatus; | ||
| import org.springframework.web.bind.annotation.ExceptionHandler; | ||
| import org.springframework.web.bind.annotation.ResponseStatus; | ||
| import org.springframework.web.bind.annotation.RestControllerAdvice; | ||
|
|
||
| import java.util.stream.Collectors; | ||
|
|
||
| @RestControllerAdvice | ||
| public class ArticleExceptionHandler { | ||
| @ExceptionHandler(ConstraintViolationException.class) | ||
| @ResponseStatus(HttpStatus.BAD_REQUEST) | ||
| public ErrorResponse handleBadGatewayException(ConstraintViolationException ex) { | ||
| return new ErrorResponse("Неверно заполнены поля.", | ||
| ex.getConstraintViolations().stream() | ||
| .collect(Collectors.toMap( | ||
| violation -> violation.getPropertyPath().toString(), | ||
| ConstraintViolation::getMessage))); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| package org.javaspringcourse.exception; | ||
|
|
||
| import java.util.Map; | ||
|
|
||
| public record ErrorResponse(String message, Map<String, String> errors) {} |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| package org.javaspringcourse.service; | ||
|
|
||
| import jakarta.validation.Valid; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.javaspringcourse.dto.ArticleIn; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.validation.annotation.Validated; | ||
|
|
||
| @Slf4j | ||
| @Service | ||
| @Validated | ||
| public class ArticleService { | ||
| public String create(@Valid ArticleIn article) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Вообще такой подход имеет место (использовать аннотации валидации на уровне сервиса) и как правило применяется не к самому сервису, а к его интерфейсу. Но все же, на будущее, следует валидации выполнять на уровне контроллера. Как правило во всех проектах у тебя должны быть обработчики и на MethodArgumentNotValidException, и на ConstraintViolationException |
||
| var ans = "Creating a new article: " + article.toString(); | ||
| log.info(ans); | ||
| return ans; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| package org.javaspringcourse.validation; | ||
|
|
||
| import jakarta.validation.Constraint; | ||
| import jakarta.validation.Payload; | ||
| import jakarta.validation.constraints.NotBlank; | ||
|
|
||
| import java.lang.annotation.ElementType; | ||
| import java.lang.annotation.Retention; | ||
| import java.lang.annotation.RetentionPolicy; | ||
| import java.lang.annotation.Target; | ||
|
|
||
| @NotBlank | ||
| @Constraint(validatedBy = RussianFullNameConstraintValidator.class) | ||
| @Retention(RetentionPolicy.RUNTIME) | ||
| @Target(ElementType.FIELD) | ||
| public @interface RussianFullName { | ||
| String message() default "Введённое ФИО не соответствует формату: \"Фамилия Имя Отчество\" (допускаются двойные фамилии)."; | ||
|
|
||
| Class<?>[] groups() default {}; | ||
|
|
||
| Class<? extends Payload>[] payload() default {}; | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| package org.javaspringcourse.validation; | ||
|
|
||
| import jakarta.validation.ConstraintValidator; | ||
| import jakarta.validation.ConstraintValidatorContext; | ||
|
|
||
| import java.util.Arrays; | ||
| import java.util.regex.Pattern; | ||
|
|
||
| /**Проверяет, соответствует ли введённая строка Фамилии-Имени-Отчеству в русском алфавите.*/ | ||
| public class RussianFullNameConstraintValidator implements ConstraintValidator<RussianFullName, String> { | ||
| @Override | ||
| public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) { | ||
| var name = s.split(" "); | ||
| if (name.length != 3) return false; | ||
| return Arrays.stream(name).allMatch(n -> Pattern.matches("^[А-Яа-я]+(-?[А-Яа-я]+)?$", n)); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| package org.javaspringcourse.validation; | ||
|
|
||
| import jakarta.validation.Constraint; | ||
| import jakarta.validation.Payload; | ||
| import jakarta.validation.constraints.NotNull; | ||
| import jakarta.validation.constraints.Size; | ||
|
|
||
| import java.lang.annotation.ElementType; | ||
| import java.lang.annotation.Retention; | ||
| import java.lang.annotation.RetentionPolicy; | ||
| import java.lang.annotation.Target; | ||
|
|
||
| @NotNull | ||
| @Size(min = 5, max = 40) | ||
| @Constraint(validatedBy = {}) | ||
| @Retention(RetentionPolicy.RUNTIME) | ||
| @Target(ElementType.FIELD) | ||
| public @interface Title { | ||
| String message() default "Длина названия должна находиться в диапазоне от 5 до 40."; | ||
|
|
||
| Class<?>[] groups() default {}; | ||
|
|
||
| Class<? extends Payload>[] payload() default {}; | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
compileOnly