@P_Alexander
First head

Как сказать валидатору что бы он обрабатывал конкретную форму в контроллере?

Добрый день. Помогите разобраться.
Использую технологии :Springmvc, Thymeleaf
Вопрос: Почему при валидации формы валидатор пытается валидировать другую форму, хотя в аннотоции @InitBinder я указал что именно валидировать!?
Есть страница регистрации с формой , ей в шапку встраивается навБар а в нем есть еще форма.

Контроллер
Controller("SignUpController")
public class SignUpController {

    private final Logger logger = LogManager.getLogger(SignUpController.class);

    private SearchPassportForm searchPassportForm = new SearchPassportForm();

    @Autowired
    private CustomerService customerService;

    @Autowired
    @Qualifier("customerValidator")
    private CustomerValidator customerValidator;

    @InitBinder("customer")
    private void customerValidation(WebDataBinder webDataBinder) {
        webDataBinder.addValidators(customerValidator);
    }

    @RequestMapping(value = "/signUp", method = RequestMethod.GET)
    public String signUp(Model model) {
        model.addAttribute("searchPassportForm", searchPassportForm);
        model.addAttribute("customer", new Customer());
        return "signUp";
    }

    @RequestMapping(value = "/signUp", method = RequestMethod.POST)
    public String regCustomer(@Valid @ModelAttribute("customer") Customer customer
                                , BindingResult bindingResult) {
        Customer cus = customer;
        logger.debug("SIGH-UP login customer " +  cus.toStringLogin());

        if ( bindingResult.hasErrors()) {
            return "signUp";
        }

        return "redirect:/home";
    }


Валидатор
@Service
public class CustomerValidator implements org.springframework.validation.Validator {

    private static final Logger logger = LogManager.getLogger(CustomerValidator.class);
    @Autowired
    private javax.validation.Validator validator;

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

    @Override
    public void validate(Object o, Errors errors) {
        Set<ConstraintViolation<Object>> validates = validator.validate(o);

        for (ConstraintViolation<Object> constraintViolation: validates) {
            String propertyPath = constraintViolation.getPropertyPath().toString();
            String message = constraintViolation.getMessage();
            logger.debug(propertyPath + " :: propertyPath");
            logger.debug(message + " :: message");
            errors.rejectValue(propertyPath, "", message);
        }

        Customer customer = (Customer)o;
        if (customer.getAge() < 0) {
            errors.rejectValue("age", "value.negative");
        }
    }
}


Вывод ошибки
17:25:58,974 ERROR [org.thymeleaf.TemplateEngine] (default task-1) [THYMELEAF][default task-1] Exception processing template "signUp": An error happened during template parsing (template: "ServletContext resource [/WEB-INF/views/signUp.html]"): org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "ServletContext resource [/WEB-INF/views/signUp.html]")
	at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:241)
	at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parseStandalone(AbstractMarkupTemplateParser.java:100)
w.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
	at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
	at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
	at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
	at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
	at org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
	at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
	at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
	at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
	at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
	at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
	at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
	at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
	at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
	at io.undertow.server.Connectors.executeRootHandler(Connectors.java:364)
	at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
	at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
	at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
	at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
	at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
	at java.lang.Thread.run(Thread.java:748)
Caused by: org.attoparser.ParseException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "patternViews/navbar" - line 21, col 67)
	at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393)
	at org.attoparser.MarkupParser.parse(MarkupParser.java:257)
	at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:230)
Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'searchPassportForm' available as request attribute
	at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153)
	at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:897)
	at org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext.getBindStatus(SpringWebMvcThymeleafRequestContext.java:227)
	at org.thymeleaf.spring5.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:305)
	at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:252)
	at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:226)
	at org.thymeleaf.spring5.processor.AbstractSpringFieldTagProcessor.doProcess(AbstractSpringFieldTagProcessor.java:174)
	at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74)
  • Вопрос задан
  • 87 просмотров
Решения вопроса 1
@P_Alexander Автор вопроса
First head
Фух!
Дело было не в валидаторе а в том что если есть форма на странице для ние нужно в модель передать обьект.
Вопрос решился так:
if ( bindingResult.hasErrors()) {
            model.addAttribute("searchPassportForm", searchPassportForm);
            return "signUp";
        }
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы