我在添加用户方法中将包含输入字段值的对象发送到 Controller 时遇到问题。它会生成由选择框引起的错误(“错误请求”)。 表连接运行良好,我可以打印用户列表并添加用户窗口,但添加用户不起作用。
代码:
实体类片段(还有带有 hibernate 注释的 getter 和 setter)
@Entity
@Table(name = "user_emes")
public class UserEmes implements java.io.Serializable {
private long idUser;
private String code;
private String name;
private String surname;
private Permission permission; -> object from another Table called "permissions"
private String login;
private String password;
private boolean isActive;
...
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "id_permissions")
public Permission getPermission() {
return permission;
}
Controller
@RequestMapping(value = "/addUser", method = RequestMethod.GET)
public String userForm(Model model) {
model.addAttribute("user", new UserEmes());
return "index";
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public ModelAndView addUser(@ModelAttribute("user") UserEmes userEmes) {
emesUserService.addUser(userEmes);
return new ModelAndView("redirect:/all-users");
}
Html(选择框):
<div class="form-group input-group has-feedback">
<span class="input-group-addon"> <label>UPRAWNIENIA</label>
</span>
<div
th:if="${permissionsList != null and not #lists.isEmpty(permissionsList)}">
<select class="form-control" name="permission">
<option th:each="dropDownItem : ${permissionsList}"
th:value="${dropDownItem.getIdPermission()}"
th:text="${dropDownItem.toString()}" />
</select>
</div>
一些截图: List of users Add user
这就是它的样子。正如您所看到的,权限列表已正确加载到选择框,并且当您填写其余字段时,它会在空白屏幕上显示“错误请求”错误。
thymeleaf 可以做这样的事情吗? 我正在等待您的答复。
最佳答案
您应该使用 tymeleaf backbean 绑定(bind)来实现非原始 ID
<select th:object="${user}" th:field="*{permission} class="form-control" name="permission">
<option th:each="dropDownItem : ${permissionsList}"
th:value="${dropDownItem.getIdPermission()}"
th:text="${dropDownItem.toString()}" />
</select>
这样,您将不让 thymeleaf 将权限属性绑定(bind)到给定的选择字段(和选项)。注意 th:object
、th:field
和 *
运算符,这不是拼写错误,这里应该使用星号而不是 $
。
检查 Spring-Thymeleaf 集成的文档,那里有描述
http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html并检查如何创建选择
输入。
PS:这是我的一个项目中的 select
字段示例
<div class="form-group" th:classappend="${#fields.hasErrors('city') ? 'has-error' : _}">
<label class="control-label" for="place-city">City</label>
<select class="form-control" id="place-city" th:field="*{city}">
<option value="" selected>----SELECT CITY----</option>
<option th:each="city : ${allCities}" th:value="${city.id}" th:text="${city.name}"></option>
</select>
<span class="help-block" th:each="msg : ${#fields.errors('addressLine')}" th:text="${msg}">Some error message for this field</span>
</div>
Controller 端:
@PostMapping(value = "/add")
@Transactional
public String addPlacePost(@Valid final Place place, BindingResult placeValidation, Model model) {
其中根实体是具有私有(private)城市
属性的Place
。
关于java - Spring Thymeleaf 从选择选项发送对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47014727/