如何将表单中的值绑定到自定义对象中

时间:2019-03-04 17:18:47

标签: java jquery ajax spring

我有一个表单,供用户输入他的值,他还必须从两个下拉菜单中进行选择。 这两个下拉菜单(国家和公司类型)应该是与用户相关的两个不同的对象。 我的问题是,这两个值的形式都是文本。因此,当我调用ajax函数时(即调用spring rest post方法),这两个值均为null。如何绑定这两个值? 先谢谢您的帮助! 在我拥有的代码下面。

我的用户对象

@Entity
@Table(name = "user")
public class User {

    @Column(name = "name")
    private String name;

    @Column(name = "last_name")
    private String lastName;

    @ManyToOne
    @JoinColumn(name = "country", foreignKey = @ForeignKey(name = "FK_country"), referencedColumnName = "name")
    @NotNull(message = "*Please select your country")
    private Country country;

    @ManyToOne
    @JoinColumn(name = "company_type", foreignKey = @ForeignKey(name = "FK_company_type"), referencedColumnName = "id")
    @NotNull(message = "*Please select your company type")
    private CompanyType companyType;

    //Getter, setter ecc
}

表格

<form id="registrationForm" th:object="${user}" method="post" onsubmit="return false;">     
    <div>
        <input id="name" type="text" th:field="*{name}" placeholder="Name"/>
    </div>
    <div>
        <input id="lastname" type="text" th:field="*{lastName}" placeholder="Lastname"/>
    </div>
    <div class="form-group">
        <select id="country" th:field="*{country.name}">
            <option value="" selected>Select Country</option>
            <option  th:each="country : ${countries}" th:value="${country.name}" th:text="${country.name}"></option>
        </select>
    </div>
    <div class="form-group">
        <select id="companyType" th:field="*{companyType.id}">
            <option value="" selected>Select Company Type</option>
            <option th:each="companyType : ${companyTypes}" th:value="${companyType.id}" th:text="${companyType.type}"></option>
        </select>
    </div>
    <div>
        <button id="register"  type="submit" class="btn btn-3 btn-rounded ml-auto" onclick="saveUser();">Register</button>
    </div>
</form>

ajax调用

function saveUser(){
    var country = $("#companyType option:selected").val();
    var companyType = $("#country option:selected").val();
        $.ajax({
            type: "post", // method attribute of form
            url: "registerUser",  // action attribute of form
            data : {
                "name" : $("#name").val(),
                "lastName" : $("#lastname").val(),
                "companyType" : companyType,
                "country" : country
            },
            success: function(data) {
                console.log(data);
                return data; 
            },              
            error: function(data) {
                console.log(data);
                return data; 
            }
         });
}

我的控制器

@PostMapping(value = "/registerUser")
    public void createNewUser(User user, BindingResult bindingResult) {        
        userService.saveUser(user);
}

0 个答案:

没有答案