【问题标题】:Can't reach the object from thymeleaf无法从百里香到达物体
【发布时间】:2017-04-26 13:44:09
【问题描述】:

我有一个带有 spring boot/thymeleaf 的简单项目,我遇到了关于从 thymeleaf 访问对象的问题。 我有我的用户和角色对象。这是我的用户实体:

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    @Column(unique = true)
    private String username;
    private String password;
    private int enabled;
    @ManyToOne
    private Role role;

    // getters and setters...

}

和角色实体:

@Entity
@Table(name = "roles")
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String role;

    // getters and setters...
}

我提供对象的控制器:

@RequestMapping(value = "edit", method = RequestMethod.GET)
public ModelAndView editRoles(){
    ModelAndView modelAndView= new ModelAndView();
    modelAndView.addObject("users", userService.getAll());
    modelAndView.addObject("roles", roleService.getAll());
    modelAndView.setViewName("editRole");
    System.out.println(userService.findUser(2).getRole().getRole());
    return modelAndView;
}

在页面上,我尝试使用选择框编辑用户角色。我希望它将用户角色显示为选定的值。但它不起作用。这是代码:

<tr th:each="user : ${users}">
    <td >
        <select class="form-control" id="sel1" th:field="*{roles}" >
            <option th:each="role : ${roles}" th:value="${role.id}" th:text="${role.role}" th:selected="${user.role.role}">
            </option>
        </select>
    </td> 
</tr>

问题在于 user.role.role 部分。它给了

SpringEL 表达式

错误。

当我使用user.role时,我可以访问角色对象;但我不能使用角色的属性。 有趣的是,当我使用具有完全相同配置的完全不同的实体时,我没有收到任何错误。

谁能告诉我这里有什么问题?

【问题讨论】:

  • th:selected 应该评估为真/假,而不是字符串。此外,如果您使用的是th:field,则不必使用th:selected -- thymeleaf 会为您执行此操作。
  • 这是使用选择框的一个问题。您对我为什么无法访问该对象有任何意见吗?
  • 主要原因是您没有正确地将对象从控制器传递到 HTML,希望您能像我在下面显示的那样遵循 :)
  • 我解决了。这是一个菜鸟错误:) 我正在传递对象,但其中有一个空值,这就是问题 :D 感谢你们俩

标签: java spring spring-boot thymeleaf


【解决方案1】:

控制器

@RequestMapping(value = "/create", method = RequestMethod.GET)
public String method1(Model model, Principal principal) {
    model.addAttribute("editRole", roles);
    return "HTML_NAME";
}

控制器 2

@RequestMapping(value = "/edit", method = RequestMethod.POST)
public String campaignPost(@ModelAttribute("roles") Roles roles,  Principal principal){
    roles.getName();
    //roles object can be accessed
}

HTML

<form th:action="@{/edit}" method="post" id="formName">
    <select class="form-control" th:value="${objectparamater}" name="gender" id="gender">
        <option disabled="disabled" selected="selected" > -- select the location --</option>
        <option>male</option>
        <option>female</option>
        <option>choose not to tell</option>
    </select>
</form>

我想这可能对你有帮助

【讨论】:

    猜你喜欢
    • 2018-07-08
    • 2017-06-29
    • 1970-01-01
    • 2020-12-30
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    • 2020-05-17
    相关资源
    最近更新 更多