gpt4 book ai didi

spring-mvc - Thymeleaf 和 Spring Boot 的下拉列表

转载 作者:行者123 更新时间:2023-12-01 19:34:13 27 4
gpt4 key购买 nike

我有一个在 HTML 上使用 Thymeleaf 的 Spring Boot 1.3 应用程序。我有用户页面,当我编辑它们时,我希望从列表中选择用户机构。我的窗口正确显示了所有内容,但是当我选择机构时, Controller 不显示所选值。

这是我的 HTML:

 <div class="form-group">
<label class="col-md-3 control-label">Institution</label>
<div class="col-md-5">
<div th:if="${institutionList != null and not #lists.isEmpty(institutionList)}">
<select>
<option th:each="dropDownItem : ${institutionList}"
th:value="${dropDownItem.name}"
th:text="${dropDownItem.name}" />
</select>
</div>
<div th:if="${institutionList == null or lists.isEmpty(institutionList)}">
<div>"No Institutions were found, please create some first"</div>
</div>
</div>
</div>

这是我的 Controller

@Controller
@PreAuthorize("hasRole('Admin')")
@RequestMapping("/admin")
public class AdminController {
@Transactional
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String checkPersonInfo(@ModelAttribute User user, Model model, Authentication authentication) {
// user does not have the selected institution set
customUserDetailsService.createNewUser(user);
updateModelWithAllUsers(model);
return "admin";
}

private void updateModelWithAllUsers(Model model) {
model.addAttribute(USERLIST, customUserDetailsService.findAllUsers());
model.addAttribute(INSTITUTION_LIST, institutionService.findAll());
model.addAttribute("user", new User());
}

...
}

这是我的用户:

@Entity
@Table(name = "Users")
public class User implements UserDetails {
@Id
private String username;

@Column(nullable = false)
private String password;

private boolean enabled;
private boolean accountNonExpired;
private boolean accountNonLocked;
private boolean credentialsNonExpired;
private String companyName;
private String email;

@ElementCollection(fetch=FetchType.EAGER)
@CollectionTable(name="Authorities", joinColumns=@JoinColumn(name="username"))
@Column(name="authority")
private Set<String> roles = new HashSet<String>();

@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "institutionId", nullable = false)
private Institution institution;
... getters & setters
}

还有我的机构:

@Entity
@Table(name = "Institution")
public class Institution {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long institutionId;
private String name;

@OneToMany(mappedBy = "institution", fetch = FetchType.EAGER)
@Fetch(value = FetchMode.SUBSELECT)
List<User> users = new ArrayList<User>();
... getters & setters
}

当“/addUser”从用户界面获取用户对象时,机构为空。

编辑我使用 Sergios 建议使用 select th:field="${user.institution}" 以及 select th:field="*{institution}"

但这给了我一个错误:

org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'user' on field 'institution': rejected value [com.security.Institution@3e3945d2]; codes [typeMismatch.user.institution,typeMismatch.institution,typeMismatch.com. .security.Institution,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.institution,institution]; arguments []; default message [institution]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.security.Institution' for property 'institution'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type java.lang.Long for value 'com.security.Institution@3e3945d2'; nested exception is java.lang.NumberFormatException: For input string: "com. .security.Institution@3e3945d2"]

不确定我是否理解正确,但这是否意味着 Thymeleaf 正在尝试将 Institution.name 传递给 user.institution 字段?

任何人都可以就如何做到这一点提供任何建议吗?

最佳答案

您忘记指出必须从中获取所选值的字段:

示例:我假设 User 类具有机构属性。

<div class="form-group">
<label class="col-md-3 control-label">Institution</label>
<div class="col-md-5">
<div th:if="${institutionList != null and not #lists.isEmpty(institutionList)}">
<select th:field="*{institution}">
<option th:each="dropDownItem : ${institutionList}"
th:value="${dropDownItem.name}"
th:text="${dropDownItem.name}" />
</select>
</div>
<div th:if="${institutionList == null or lists.isEmpty(institutionList)}">
<div>"No Institutions were found, please create some first"</div>
</div>
</div>

更多信息:http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#dropdownlist-selectors

编辑:您需要向您的应用指示如何将表单(字符串类型)内返回的机构 ID 转换为机构实体。为此,您必须使用转换器。

首先将option的值改为institutionId:

<div class="form-group">
<label class="col-md-3 control-label">Institution</label>
<div class="col-md-5">
<div th:if="${institutionList != null and not #lists.isEmpty(institutionList)}">
<select th:field="*{institution}">
<option th:each="dropDownItem : ${institutionList}"
th:value="${dropDownItem.institutionId}"
th:text="${dropDownItem.name}" />
</select>
</div>
<div th:if="${institutionList == null or lists.isEmpty(institutionList)}">
<div>"No Institutions were found, please create some first"</div>
</div>
</div>

您必须创建一个实现 Converter 接口(interface)的类。

@Component
public class StringToInstitution implements Converter<String, Institution> {

@Autowired
private InstitutionRepository repository; //Or the class that implments the repository.

@Override
public Institution convert(String arg0) {
Long id = new Long(arg0);
return repository.findOne(id);
}

}

关于spring-mvc - Thymeleaf 和 Spring Boot 的下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35701905/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com