Гость
Форумы / Java [игнор отключен] [закрыт для гостей] / Не работает Spring Validation в Spring Boot 2 / 4 сообщений из 4, страница 1 из 1
18.09.2019, 19:51
    #39863559
Tsyklop
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Не работает Spring Validation в Spring Boot 2
Хочу сделать валидировать входящие данные при помощи 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
18.09.2019, 19:57
    #39863560
Tsyklop
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Не работает Spring Validation в Spring Boot 2
разобрался
...
Рейтинг: 0 / 0
19.09.2019, 14:59
    #39864009
Molasar
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Не работает Spring Validation в Spring Boot 2
Какая была причина?
Tsyklopразобрался
...
Рейтинг: 0 / 0
19.09.2019, 22:06
    #39864245
Tsyklop
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Не работает Spring Validation в Spring Boot 2
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
Форумы / Java [игнор отключен] [закрыт для гостей] / Не работает Spring Validation в Spring Boot 2 / 4 сообщений из 4, страница 1 из 1
Целевая тема:
Создать новую тему:
Автор:
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


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