首页 > 解决方案 > 无法使用 th:object 在 Spring Boot 中加载页面

问题描述

它包含一行错误:“模板解析期间发生错误(模板:“类路径资源 [templates//register.html]”)”。我无法打开注册 html 页面以将新对象添加到数据库中。为什么?

<form th:action="@{/register-user}" th:object="user" method="post">
        <div class="form-group">
            <label for="email">Email:</label>
            <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
        </div>
        <div class="form-group">
            <label for="password">Password:</label>
            <input type="password" class="form-control" id="password" placeholder="Enter password" name="pswd">
        </div>
        <div class="form-group form-check">
        </div>
        <button type="submit" class="btn btn-primary">Register</button>
    </form>

我的控制器

@RequestMapping(path="/register-user", method = RequestMethod.POST)
    public String registerNewUser(@Valid @ModelAttribute("user") User user){
        userService.register(user);
        return "redirect:/login";
    }

标签: spring-bootthymeleaf

解决方案


您的“用户”是一个模型属性,因此,要访问它(并将其用作th:object),您必须使用${...}语法。结果将如下所示:

<form th:action="@{/register-user}" th:object="${user}" method="post">

推荐阅读