无法显示表单支持bean的验证错误

时间:2014-07-09 00:30:55

标签: java spring-mvc thymeleaf

我很难在Spring MVC应用程序中使用表单支持bean和该表单支持bean中的复杂对象来显示验证错误。

似乎“hasErrors”功能不支持“。”字符或无法解析复杂对象?

加载以下代码时,我可以显示表单。但是,在验证器找到空作者姓名并重新加载create.html页面后,我得到一个关于Thymeleaf / Spring如何无法评估我的SPel表达式的堆栈跟踪。

当表达式声明“author.name”时,是否有人知道为什么要尝试加载“ author.author ”?这就好像该物业正在获得“作者”。在表达之前。

更新 经过大量的故障排除后,我发现验证器是问题,虽然我不知道为什么。

我已经包含了验证器。

AuthorCommandObject.java

public class AuthorCommandObject {
    private Author _author;
    private Book _book;

    public Author getAuthor() {
        return _author;
    }

    public void setAuthor(Author author) {
        _author = author;
    }

    public Author getBook() {
        return _book;
    }

    public void setBook(Book book) {
        _book = book;
    }
}

Author.java

public class Author {
    private long _authorId;
    private String _name;

    public long getAuthorId() {
        return _authorId;
    }

    public void setAuthorId(long authorId) {
        _authorId = authorId;
    }

    public String getName() {
        return _name;
    }

    public void setName(String name) {
        _name = name;
    }
}

Book.java

public class Book {
    private long _bookId;
    private String _bookName;

    public long getBookId() {
        return _bookId;
    }

    public void setBookId(long bookId) {
        _bookId = bookId;
    }

    public String getName() {
        return _name;
    }

    public void setName(String name) {
        _name = name;
    }
}

AuthorFormController.java

    @Controller
    @RequestMapping("/author")
    public class AuthorFormController {

        @InitBinder("authorCommandObject")
        public void initBinder(WebDataBinder binder) {
            binder.setValidator(new AutherCommandObjectValidator(new AuthorValidator(), new BookValidator()));      
        }

        @RequestMapping(method=RequestMethod.GET, value ="/create", produces = "text/html")
        public String createForm(Model model) {
            AuthorCommandObject authorCommandObject = new AuthorCommandObject();
            authorCommandObject.setAuthor(new Author());
            authorCommandObject.setBook(new Book());
            model.addAttribute("authorCommandObject", authorCommandObject);
            return "/author/create";
        }

        @RequestMapping(method=RequestMethod.POST, value ="/save", produces = "text/html")
        public String save(@Valid @ModelAttribute("authorCommandObject") AuthorCommandObject authorCommandObject, BindingResult result, Model model) {


        if (result.hasErrors()) {
            return "/author/create";
        }

        // the rest of the logic here

        }
    }

create.html上

    <form th:action="@{/author/save}" method="POST" class="form-horizontal" th:object="${authorCommandObject}">
        Author Name:<input type="text" th:field="*{author.name}" />
        <ul th:if="${#fields.hasErrors('author.name')}">
            <li th:each="err : ${#fields.errors('author.name')}" th:text="${err}" />
        </ul>
        <input type="submit" value="Submit" class="btn btn-primary btn-lg" />
    </form>

AuthorCommandObjectValidator.java

public class AuthorCommandObjectValidator implements Validator {

    private final Validator _authorValidator;
    private final Validator _bookValidator;

    public AuthorCommandObjectValidator(Validator authorValidator, Validator bookValidator) {
        _authorValidator = authorValidator;
        _bookValidator = bookValidator;
    }

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

    @Override
    public void validate(Object obj, Errors errors) {
        AuthorCommandObject authorCommandObject = (AuthorCommandObject)obj; 
        try {
            errors.pushNestedPath("author");
            ValidationUtils.invokeValidator(_authorValidator, authorCommandObject.getAuthor(), errors);

            errors.pushNestedPath("book");
            ValidationUtils.invokeValidator(_bookValidator, authorCommandObject.getBook(), errors);
        } finally {
            errors.popNestedPath();
        }
    }
}

AuthorValidator.java

public class AuthorValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return Author.class.equals(clazz);
    }

    @Override
    public void validate(Object obj, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "field.required");
    }
}

部分Stacktrace(最后一行是最有帮助的)

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#fields.hasErrors('author.name')"
org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#fields.hasErrors('author.name')"
org.springframework.beans.NotReadablePropertyException: Invalid property 'author.author' of bean class [com.sample.application.AuthorCommandObject]: Bean property 'author.author' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?

1 个答案:

答案 0 :(得分:0)

您之前需要这种标签:

<div th:object="${form}" th:remove="tag"> <ul> <li th:each="err : ${#fields.errors('*')}" th:text="${err}" /> </ul> </div>