P
P
P_Alexander2019-10-13 17:41:58
Java
P_Alexander, 2019-10-13 17:41:58

How to tell the validator to process a specific form in the controller?

Good afternoon. Help me to understand.
I use technologies :Springmvc, Thymeleaf
Question: Why, when validating a form, the validator tries to validate another form, although I specified what to validate in the @InitBinder annotation!?
There is a registration page with a form, a navBar is built into the header, and there is also a form in it.
Controller

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";
    }

Validator
@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");
        }
    }
}

Error output
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)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
P_Alexander, 2019-10-13
@P_Alexander

Phew!
The point was not in the validator, but in the fact that if there is a form on the page for them, you need to transfer the object to the model.
The issue was resolved like this:

if ( bindingResult.hasErrors()) {
            model.addAttribute("searchPassportForm", searchPassportForm);
            return "signUp";
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question