首页 > 解决方案 > 如何使用spring boot在thymleaf中设置聚合对象的输入字段

问题描述

我正在尝试使用 Spring Boot 为 thymleaf 中的聚合对象设置输入字段。我的模型是

public class DearHelpUsers {

    private String id;
    private String username;
    private String email;
    private String password;
    private String cnfPassword;
    private String role;
    private String phoneNumber;
    private UserAddress address;

    //setters getters
}

我在 DearHelpUsers 类中聚合 UserAddress 类

class UserAddress{

    private String streetName;
    private String city;
    private String zipCode;
    private String state;
    private float lattitude;
    private float longitude;

    //setters and getters
}

我的百里香形式是“regfuser.html”

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Handling Form Submission</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
	<h1>Form</h1>
    <form action="#" th:action="@{/register}" th:object="${user}" method="post">
    	<p>Username: <input type="text" th:field="*{userName}" /></p>
        <p>Password: <input type="text" th:field="*{password}" /></p>
        <p>Confirm Password: <input type="text" th:field="*{cnfPassword}" /></p>
        <!-- other fields-->
        <p>Street: <input type="text" th:field="*{}" /></p>
        <p>City: <input type="text" th:field="*{}" /></p>
        <p>Zip: <input type="text" th:field="*{}" /></p>
        <p>State: <input type="text" th:field="*{}" /></p>
        <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
    </form>
</body>
</html>

我的控制器是

@Controller
public class DearHelpUsersController {

@Autowired
private DearHelpUsersRepo userRepo;

@GetMapping("/regfuser")
public String regUserForm( Model model) {
    model.addAttribute("user" new DearHelpUsers());
    return "regfuser";
}

我已将“用户”对象从我的控制器传递到此表单。如何在我的表单中设置 UserAddress 属性的字段?希望有人能尽快帮助我。

标签: spring-bootthymeleaf

解决方案


您可以使用:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Handling Form Submission</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <h1>Form</h1>
    <form action="#" th:action="@{/register}" th:object="${user}" method="post">
        <p>Username: <input type="text" th:field="*{userName}" /></p>
        <p>Password: <input type="text" th:field="*{password}" /></p>
        <p>Confirm Password: <input type="text" th:field="*{cnfPassword}" /></p>
        <!-- other fields-->
        <p>Street: <input type="text" th:field="*{address.streetName}" /></p>
        <p>City: <input type="text" th:field="*{address.city}" /></p>
        <p>Zip: <input type="text" th:field="*{address.zipCode}" /></p>
        <p>State: <input type="text" th:field="*{address.state}" /></p>
        <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
    </form>
</body>
</html>

推荐阅读