【问题标题】:how the values transfer between thymeleaf and spring controller, viceversathymeleaf 和 spring 控制器之间的值如何传递,反之亦然
【发布时间】:2013-05-31 19:17:18
【问题描述】:

我是 thymeleaf 的新手...有人能告诉我值是如何在 thymeleaf html 和 spring 控制器之间传递的吗...请为 thymeleaf-spring-mvc 推荐好的教程...

在下面的例子中,请让我知道用户在文本字段中输入的所有者值是如何传递给 spring 控制器的,以便它验证并返回结果。反之亦然,控制器返回的结果如何由 thymeleaf 获取以显示结果。控制器如何知道 LASTNAME 的值。如何将其传递给控制器​​的所有者对象 owner.getLastName() ..

寻找所有者

<form th:object="${owner}" action="ownersList.html" th:action="@{'/owners.html'}" method="get" class="form-horizontal"
           id="search-owner-form">
    <fieldset>
        <div class="control-group" id="lastName">
            <label class="control-label">Last name </label>
            <input type="text" th:field="*{lastName}" size="30" maxlength="80"/>
            <span class="help-inline" th:errors="*{lastName}">[Errors]</span>
        </div>
        <div class="form-actions">
            <button type="submit">Find Owner</button>
        </div>
    </fieldset>
</form>

@RequestMapping(value = "/owners", method = RequestMethod.GET) public String processFindForm(Owner owner, BindingResult result, Model model) {

    // allow parameterless GET request for /owners to return all records
    if (owner.getLastName() == null) {
        owner.setLastName(""); // empty string signifies broadest possible search
    }

    // find owners by last name
    Collection<Owner> results = this.clinicService.findOwnerByLastName(owner.getLastName());
    if (results.size() < 1) {
        // no owners found
        result.rejectValue("lastName", "notFound", "not found");
        return "owners/findOwners";
    }
    if (results.size() > 1) {
        // multiple owners found
        model.addAttribute("selections", results);
        return "owners/ownersList";
    } else {
        // 1 owner found
        owner = results.iterator().next();
        return "redirect:/owners/" + owner.getId();
    }
}

【问题讨论】:

    标签: html spring-mvc spring-3 thymeleaf


    【解决方案1】:

    假设你有一个控制器方法,比如:

    void method-name(Owner owner){
        // ...
    }
    

    单击提交按钮时,值会自动设置为域类,在此之前创建一个新方法并设置对象的模型属性 model.addAttribute("owner",new Owner);

    【讨论】:

    • model 属性仅适用于 th:object 标签,或者是否需要为 thymeleaf 中声明的每个变量定义 model 属性...
    • 不,它不仅适用于 th:object ,你可以指定一个列表,为你想要的任何值。
    猜你喜欢
    • 2017-02-18
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 2010-09-29
    相关资源
    最近更新 更多