【问题标题】:Thymeleaf cannot find declarationThymeleaf 找不到声明
【发布时间】:2021-03-29 16:59:50
【问题描述】:

我对百里香叶有疑问。在 html 文件中找不到 newUser 模型。

<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>

来自这个班级:

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";
    }
}

问题是从其他类和 html 可以正常工作。

你能告诉我有什么问题吗?

【问题讨论】:

  • 模型属性是请求属性,但您正在执行重定向。使用会话/闪存属性,或更改您的 /login 处理程序以自行添加这两个属性。

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


【解决方案1】:

确保在您的 LoginUser 中添加这一行:

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

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

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

【讨论】:

  • 谢谢,第二个解决方案使用返回“注册”,但为什么我必须在重定向时在登录方法中定义 newUser 和角色?
  • 一个返回视图,而后者重定向到另一个控制器请求映射操作
猜你喜欢
  • 2011-09-20
  • 1970-01-01
  • 1970-01-01
  • 2015-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多