简体   繁体   English

Spring Boot Thymeleaf 下拉列表

[英]Spring Boot Thymeleaf Dropdown List

I'm trying to persist values in database from a dropdown list in Spring Boot , thymeleaf but the database is populated with empty values.我正在尝试从Spring Boot thymeleaf的下拉列表中保留数据库中的值,但数据库中填充了空值。

Apparently the controller doesn't pass the value.显然控制器没有传递值。

While I can fetch and display the values in GET but I cannot persist them in POST .虽然我可以在GET 中获取和显示值,但我不能在POST 中保留它们。

I'm not able to get a clear example from anywhere and even the examples on Thymeleaf are not clear.我无法从任何地方获得清晰的示例,甚至Thymeleaf上的示例也不清楚。

Please help with some good example or a solution.请帮助一些好的例子或解决方案。

The code is as below.代码如下。

@Controller
public class HomeController {

    @RequestMapping(value = "/signup", method = RequestMethod.POST)
    public String signupPost(@ModelAttribute("user") User user,
        Model model, BindingResult result) {

        if (!result.hasErrors()) {
            userService.saveUser(user);
        }
        return "redirect:/";

    }

}

The User class is as below User类如下

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "user_id", nullable = false, updatable = false)
    private Long userId;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "award_partner_id")
    private AwardPartner awardPartner;

    getters and setters....
}

The HTML snippet is here: HTML 片段在这里:

<!--Award Partner-->
<div class="form-group">
    <label class="col-md-4 control-label">Award Partner</label>
    <div class="col-md-6 selectContainer">
        <div class="input-group">
            <span class="input-group-addon"><i
                class="glyphicon glyphicon-list"></i></span> 
                <select name="awardPartner" roleId="awardPartner" id="awardPartner"
                th:field="*{awardPartner}" class="form-control selectpicker">
                <option value="">Select Award Partner</option>
                <option th:each="awardPartner : ${awardPartners}"
                    th:value="${awardPartner.id}"
                    th:text="${awardPartner.title}"></option>
            </select>
        </div>
    </div>
</div>

<!-- end snippet -->

In your form tag, I think there is th:object="user" .在您的表单标签中,我认为有th:object="user"

In your select tag, there is th:field="*{awardPartner}" .在您的选择标签中,有th:field="*{awardPartner}" It means that you will put the selected value (the value of the selected option tag) in the field awardPartner of the object user.这意味着您将把选定的值(选定选项标签的值)放在对象用户的字段 AwardPartner 中。 This field awardPartner is of type AwardPartner该字段awardPartner的类型是AwardPartner

In the option values, you have got an id (int or string?) as value but not an object of type AwardPartner在选项值中,您有一个 id(整数或字符串?)作为值,但不是AwardPartner类型的对象

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM