Thymeleaf将对象发布到控制器

时间:2018-12-19 15:22:35

标签: java spring spring-mvc spring-boot thymeleaf

我是Thymeleaf的新手,我试图将对象发布到控制器,但未获得任何成功。这是我正在使用的表单模板:

<form id="customerRecord" th:action="@{/saveData}" method="post" th:object="${customerData}">
    <input type="hidden" th:value="${name}" th:field="*{name}">
    <button type="submit" class="btn btn-primary" >Save Record</button>
</form>

控制器:

@PostMapping("/saveData")
public String saveCustomerData(@ModelAttribute("customerData") CustomerData customerData, Model model) {
    try {
        LOG.info("Working {}", writer.writeValueAsString(customerData));
    } catch (JsonProcessingException e) {
        LOG.info("Problem");
    }
    return "success";
}

CustomerData类:

public class CustomerData {
    private AuthorizeRequestItem name;
    private AuthorizeRequestItem mobileNumber;
    private AuthorizeRequestItem countryCode;
    private AuthorizeRequestItem emailUser;
    private AuthorizeRequestItem emailDomain;
}

AuthorizeRequestItem类:

public class AuthorizeRequestItem {
    private Date date;
    private String validator;
    private Boolean valid;
    private String data;
}

问题是CustomerData,它本身包含嵌套对象。

我需要将完整的CustomerData传递给控制器​​,但是当我尝试在输入字段中传递对象时,它(控制器)收到的CustomerData嵌套对象的空值。

我已经实现了Thymeleaf表单来传递包含字符串变量的对象,这对我来说很好。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

这将起作用,当我们在百里香叶中使用post时,我们将使用ajax调用,它将获取您的值并将其传递给您的控制器,当您单击Submit按钮时,值将传递给您的控制器。 例如:

 <div id="form Data">
<input  id="app Id" type="hidden" t h:value="${app Id}" />
 <input  type="submit"  on click="redirection()"/>
</div>

<script type='text/java script'>
function redirection(){
 let app id = document.get Element By Id('app Id').value;

 let u r l ="this will be your u r l where you want to redirect"

 window.open(u r l,"_self");