2017-05-19 65 views
0

我使用Spring-boot和Thymeleaf的模板引擎,我嘗試使用th:classappend屬性添加可選的「有錯誤」使用#fields.hasErrors('*')表達Thymeleaf無法綁定形式的錯誤「*」

類< DIV> HTML標籤
<form method="POST" action="/registration" class="form-signin"> 
     <h2 class="form-signin-heading">Create your account</h2> 

     <div class="form-group" th:classappend="${#fields.hasErrors('*')} ? 'has-error' : ''"> 
      <input name="username" type="text" class="form-control" placeholder="Username" autofocus="true"/> 
      <p class="alert alert-danger" th:if="${#fields.hasErrors('username')}" th:errors="*{username}"></p> 
     </div> 

     <div class="form-group" th:classappend="${#fields.hasErrors('*')} ? 'has-error' : ''"> 
      <input name="password" type="text" class="form-control" placeholder="Password" autofocus="true"/> 
      <p class="alert alert-danger" th:if="${#fields.hasErrors('password')}" th:errors="*{password}"></p> 
     </div> 

     <div class="form-group" th:classappend="${#fields.hasErrors('*')} ? 'has-error' : ''"> 
      <input name="passwordConfirm" type="text" class="form-control" placeholder="Confirm your password" autofocus="true"/> 
      <p class="alert alert-danger" th:if="${#fields.hasErrors('passwordConfirm')}" th:errors="*{passwordConfirm}"></p> 
     </div> 

     <button class="btn btn-lg btn-primary btn-block" type="submit">Submit</button> 


    </form> 

,但我有這個錯誤使用表達式「*」

無法綁定形式的錯誤。請檢查被適當情況下(例如 一個TH:對象屬​​性)內執行該 表達

我的控制器方法

@RequestMapping(value = "/registration", method = RequestMethod.GET) 
    public String registration(Model model) { 
     model.addAttribute("userForm", new User()); 

     return "registration"; 
    } 

    @RequestMapping(value = "/registration", method = RequestMethod.POST) 
    public String registration(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) { 
     userValidator.validate(userForm, bindingResult); 

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

     userService.save(userForm); 

     securityService.autologin(userForm.getUsername(), userForm.getPasswordConfirm()); 

     return "redirect:/welcome"; 
    } 

我究竟做錯了什麼?

+0

答案已經出現在你得到的錯誤中'請檢查這個表達式是否在適當的上下文中執行(例如,使用th:object屬性)'。你的表單元素應該包含一個'th:object =「$ {userForm}」'表達式,否則它不知道使用哪個命令對象。 –

+0

@ M.Deinum你是對的!謝謝! –

回答

0

我只是將th:object="${userForm}屬性添加到我的表單元素中。現在它工作正常!