powered by simpleCommunicator - 2.0.49     © 2025 Programmizd 02
Форумы / Java [игнор отключен] [закрыт для гостей] / Не работает Spring Validation в Spring Boot 2
4 сообщений из 4, страница 1 из 1
Не работает Spring Validation в Spring Boot 2
    #39863559
Tsyklop
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Хочу сделать валидировать входящие данные при помощи spring valitator.

Создал Валидатор:

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
@Component
public class PropertyValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return PropertyDTO.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "address.empty", "Address Incorrect");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "description", "description.empty", "Description Incorrect");

        PropertyDTO p = (PropertyDTO) target;

        if (Objects.isNull(p.getX())) {
            errors.rejectValue("x", "coordinate.null", "X coordinate cannot be null");
        } else if (Objects.isNull(p.getY())) {
            errors.rejectValue("y", "coordinate.null", "Y coordinate cannot be null");
        }

    }

}



Контроллер:

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
@RestController
@RequestMapping("/api/v1/property")
@RequiredArgsConstructor
public class PropertyRestController extends AbstractRestController {

    private final Validator propertyValidator;

    private final PropertyService propertyService;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(this.propertyValidator);
    }

    @GetMapping
    public ResponseEntity findAll() {
        return this.propertyService.findAll();
    }

    @GetMapping("/{x}/{y}")
    public ResponseEntity findAllByDistance(@PathVariable Double x, @PathVariable Double y, @RequestParam(name = "page", required = false, defaultValue = "0") Integer page) {
        return this.propertyService.findAllByDistance(x, y, page);
    }

    @GetMapping("/{id}")
    public ResponseEntity findById(@PathVariable Long id) {
        return this.propertyService.findById(id);
    }

    @PostMapping
    public ResponseEntity save(@Valid @RequestBody PropertyDTO property, Errors errors) {
        if(errors.hasErrors()) {
            return ResponseEntity.badRequest().body(errors.getAllErrors());
        } else {
            return this.propertyService.save(property);
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity update(@PathVariable Long id, @RequestBody PropertyDTO property) {
        return this.propertyService.update(id, property);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity deleteById(@PathVariable Long id) {
        return this.propertyService.deleteById(id);
    }

    @ExceptionHandler(PropertyException.class)
    public ResponseEntity handlePropertyException(PropertyException e) {
        return ResponseEntity.status(e.getHttpStatus()).body(e.getMessage());
    }

}



Но сам валидатор не отрабатывает. почему?

Main класс:

Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
@EntityScan
@EnableWebMvc
@SpringBootApplication
@EnableJpaRepositories
@EnableTransactionManagement
public class InteractiveMapApplication {

    @Bean(name = "multipartResolver")
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setMaxUploadSize(-1);
        return multipartResolver;
    }

    public static void main(String[] args) {
        SpringApplication.run(InteractiveMapApplication.class, args);
    }

}
...
Рейтинг: 0 / 0
Не работает Spring Validation в Spring Boot 2
    #39863560
Tsyklop
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
разобрался
...
Рейтинг: 0 / 0
Не работает Spring Validation в Spring Boot 2
    #39864009
Molasar
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Какая была причина?
Tsyklopразобрался
...
Рейтинг: 0 / 0
Не работает Spring Validation в Spring Boot 2
    #39864245
Tsyklop
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Molasar,

Вместо этого:
Код: java
1.
2.
3.
4.
@InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(this.propertyValidator);
    }



Сделал следующее:

Код: java
1.
2.
3.
4.
@InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(new PropertyValidator());
    }



Спринг, почему-то, в поле инжектит вообще левое что-то - не объект моего класса.
...
Рейтинг: 0 / 0
4 сообщений из 4, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Не работает Spring Validation в Spring Boot 2
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]