Thymeleaf 找不到声明

Thymeleaf cannot find declaration

我对百里香有疑问。在 html 文件中找不到新用户模型。

<form th:action="@{/users/add}" th:object="${newUser}" method="post">
    <p>User Name: <input type="text" th:field="*{userName}"></p>
    <p>Email:     <input type="text" th:field="*{email}"></p>
    <p>Password:  <input type="text" th:field="*{password}"></p>
    <p>Role:
        <select th:field="*{role}">
            <option th:each="role: ${roles}" th:value="${role.getId()}" th:utext="${role.getUserRole()}">
            </option>
        </select>
    </p>
    <p><input type="submit" value="Add User"></p>
</form>

从这个class:

package Application.Controllers;

@Controller
@RequestMapping("/")
public class TemplateController {

    private final RoleService roleService;

    @Autowired
    public TemplateController(RoleService roleService) {
        this.roleService = roleService;
    }

    @GetMapping("register")
    public String registerUser(Model model){
        model.addAttribute("roles", roleService.listRoles());
        model.addAttribute("newUser", new Users());
        return "redirect:login";
    }
}

问题是其他 class 和 html 工作正常。

你能告诉我哪里出了问题吗?

在您的登录用户中确保添加这一行:

 model.addAttribute("roles", roleService.listRoles());
 model.addAttribute("newUser", new Users());

或者更改 registerUser return 只是视图不要重定向到另一个操作:

   @GetMapping("register")
    public String registerUser(Model model){
        model.addAttribute("roles", roleService.listRoles());
        model.addAttribute("newUser", new Users());
        return "login";
    }