使用Thymeleaf的表格不适用于POJO

时间:2017-09-07 20:09:01

标签: java spring thymeleaf

我从Mastering Spring的书中重写代码并且它不起作用,因为我一直有例外:

Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'profileForm' available as request attribute

我的表格:

    <form th:action="@{/profile}" th:object="${profileForm}" method="post" class="col m8 s12 offset-m2">
        <div class="row">
            <div class="input-field col s6">
                <input th:field="${profileForm.twitterHandle}" id="twitterHandle" type="text"/>
                <label for="twitterHandle" th:text="#{twitter.handle}">Identyfikator Twitter</label>
            </div>
            <div class="input-field col s6">
                <input th:field="${profileForm.email}" id="email" type="email"/>
                <label for="email">Adres e-mail</label>


            </div>
        </div>
        <div class="row">
            <div class="input-field col s6">
                <input th:field="${profileForm.birthDate}" id="birthDate" type="text"/>
                <label for="birthDate" th:text="#{birthdate}">Data urodzenia</label>
            </div>
        </div>

        <div class="row s12 center">
            <button class="btn indigo waves-effect waves-light" type="submit" name="save">Wyślij
                <i class="mdi-content-send right"></i>
            </button>
        </div>
    </form>

我的POJO:

package masterspringmvc.profile;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class ProfileForm {
    private String twitterHandle;
    private String email;
    private LocalDate birthDate;
    private List<String> tastes = new ArrayList<>();

    // getters setters
}

我的控制器:

@Controller
public class ProfileController {

    @RequestMapping(value = "/profile", method = RequestMethod.GET)
    public String displayProfile() {
        return "profile/profilePage";
    }

    @RequestMapping(value = "/profile", method = RequestMethod.POST)
    public String saveProfile(ProfileForm profileForm) {
        System.out.println("Profil: " + profileForm);
        return "redirect:/profile";
    }
}

Tomcat打印显示:

Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor' (profile/profilePage:16)

根据书,一切都应该没问题,但我仍然会收到错误,为什么?

1 个答案:

答案 0 :(得分:1)

我认为你需要:

  1. 将“profileForm”添加到模型中。
  2. 将“@ModelAttribute("profileForm")”添加到帖子控制器。
  3. 此外,您可以简化@RequestMapping

    @Controller
    public class ProfileController {
        @GetMapping("/profile")
        public String displayProfile(Map<String, Object> model) {
            model.put("profileForm", new ProfileForm());
            return "profile/profilePage";
        }
    
        @PostMapping("/profile")
        public String saveProfile(@ModelAttribute("profileForm") ProfileForm profileForm) {
            System.out.println("Profil: " + profileForm);
            return "redirect:/profile";
        }
    }