【问题标题】:How to Save a Role from Thymeleaf using in Spring Boot?如何在 Spring Boot 中使用 Thymeleaf 保存角色?
【发布时间】:2020-04-25 07:56:18
【问题描述】:

大家好,我有两个模型,用户和角色。我在表角色中插入了三个角色(管理员、客户、经销商)。我已将这些角色提供给 Thymeleaf 用户类型字段,以便在注册期间选择。

角色的控制器模型属性。

@ModelAttribute("角色")

public List<Role> initializeRoles(){
    List<Role> roles = roleRepository.findAll();

    return roles ;
}

那么这里是我的thymeleaf,用于显示可供用户在注册时选择的可用角色。


 <div class="col-1.5">
        <label th:for="roles"> User Type: </label>
        <select class="form-control form-control-sm" id="agentName">
            <option value="">Select User Type</option>
            <option th:each="initializeRoles:${roles}"
                    th:value="${initializeRoles.id}"
                    th:text="${initializeRoles.name}"
            >
            </option>
        </select>
    </div>

最后是我的用户服务提交用户输入的注册数据:

public void save(User user) {
        user.setEnabled(false);
        user.setPword(new BCryptPasswordEncoder().encode(user.getPword()));
        user.setRoles(user.getRoles());
        userRepository.save(user);
    }

我希望从用户类型字段中选择的角色被提交并作为角色分配给该用户。但是,除了所选角色之外,其余用户数据都已成功保留。我哪里错了?

【问题讨论】:

  • 我认为您在
  • 谢谢@R.G,这是问题所在,现在它正在工作。谢谢一百万

标签: mysql spring spring-boot spring-data-jpa thymeleaf


【解决方案1】:

选择标记中缺少属性name

以下将解决问题

<select class="form-control form-control-sm" name="roles" id="agentName">

【讨论】:

  • 为什么 name 属性比 th:value 元素重要。这是完美的工作是的
  • name 属性用于表单提交。你可以在这里阅读更多关于它的信息stackoverflow.com/questions/1397592/…
  • th:value 这里设置可用选项的值。当表单被提交时,options中被选择的选项(值)将与select标签的名称一起提交。
猜你喜欢
  • 2018-01-13
  • 1970-01-01
  • 2019-12-30
  • 2021-04-24
  • 2017-09-01
  • 2017-09-08
  • 2017-12-10
  • 2021-06-28
  • 2017-09-30
相关资源
最近更新 更多