在发布到Api之前验证表单输入时出现Thymeleaf错误

时间:2017-04-11 09:50:07

标签: java spring validation thymeleaf spring-validator

这是我得到的错误(注意:错误 被捕获):

浏览器Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor' (forms/frmEntry:75)

STS IDE java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'e' available as request attribute at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144) ~[spring-webmvc-4.3.7.RELEASE.jar:4.3.7.RELEASE] .... ....

GET方法(显示表单):

@RequestMapping(value="/create", method=RequestMethod.GET)
public String create(Model model){

    model.addAttribute("entry", new EntryForm());

    return "forms/frmEntry";
}

由于我的原始POST方法不起作用,我尝试创建另一个更薄的POST方法,以排除与postToEntity调用Api相关的其他代码。

@PostMapping("/temp")
public String temp(@Valid @ModelAttribute EntryForm e, BindingResult bindingResult){

// returns 1 in debug mode (error for the only field (name) in the form, so OK
//      int ct = bindingResult.getErrorCount();

    if(bindingResult.hasErrors()){

        // this Thymeleaf view/template is reached
        return "forms/frmEntry";
    }

    // dummy Thymeleaf view (doesn't exist)
    return "proslodokraja";
}

我的表格:

<form action="/consumer/temp" th:object="${e}" method="post" class="col-md-6">
    // in my code, this hidden field is commented out (for now)
    <input type="hidden" th:field="*{id}" />
    <p>
        Name: <input type="text" th:field="*{name}" class="form-control" />
        <br/>
        <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name error</span>
        </p>

        <p>
            <input type="submit" value="Submit" class="btn btn-primary" /> 
            <input type="reset" value="Reset" class="btn btn-default" />
        </p>
</form>

表单Bean

public class EntryForm {

private Long id;

@NotNull
@Length(min=2) // hibernate import!
private String name;


public EntryForm(){ }

public EntryForm(String name) { this.name = name; }

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

1 个答案:

答案 0 :(得分:1)

问题出在您的模型属性名称中。您将其设置为&#34;条目&#34;,然后您尝试访问&#34; e&#34;您的frmEntry表单中的模型属性(甚至没有设置)。将您的模型属性重命名为&#34; e&#34;设置或重命名为&#34; entry&#34;在frmEntry页面上,并在@ModelAttribute中明确提供名称:

<form action="/consumer/temp" th:object="${entry}" method="post" class="col-md-6">


@ModelAttribute("entry") EntryForm e