2017-04-11 76 views
0

這之前驗證表單輸入時Thymeleaf錯誤是我得到的錯誤(注:錯誤被抓):張貼到阿比

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

STS IDEjava.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方法,以排除與調用Api的其他代碼有關的postToEntity

@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

問題是在你的模型屬性名。您將其設置爲「條目」,然後嘗試訪問frmEntry表單中的「e」模型屬性(它甚至未設置)。設置時,你的模型屬性重命名爲不是「E」或重命名爲上frmEntry頁「進入」,並明確在@ModelAttribute提供姓名:

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


@ModelAttribute("entry") EntryForm e 
+0

不太。在我發佈這個問題之前,我已經把'entry'換成了'e',因爲我試圖根據Spring的一些代碼片段來調整它。但爲了確保,我只是在模板和後期方法中都恢復了「輸入」,並且如預期那樣,錯誤仍然存​​在。 – developer10

+0

我想你畢竟是對的。我忘了在我的GET方法中也改回'entry'。最後,我決定將表單bean引用爲「entryForm」,並最終開始工作。我接受你的答案。感謝您的幫助! – developer10