JSP:如何将表单选择选项链接到Java对象

Hip*_*ray 1 javascript java jquery spring jsp

我有两个链接的对象。Address其中有CountryManyToOne由 链接的关系countryId。我正在尝试使用 JSP 添加网页来添加新的Address. 在此页面上,您可以Country从下拉列表中选择一个。

我尝试了多种不同的方法来执行此操作,但我似乎无法将Country下拉列表中的对象链接到 中的Country对象Address,我不断收到以下错误

Field error in object 'address' on field 'country': rejected value [com.company.project.domain.Country@670b11d7]; codes [typeMismatch.address.country,typeMismatch.country,typeMismatch.com.company.project.domain.Country,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [address.country,country]; arguments []; default message [country]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.company.project.domain.Country' for property 'country'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.company.project.domain.Country] for property 'country': no matching editors or conversion strategy found
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的许多不同选项中的两个,但我不断收到相同的错误

尝试 1 JAVA

List<Country> countries = countryService.getAllCountrys();
    LinkedHashMap<Country, String> countryMap = new LinkedHashMap<Country, String>();
    for(Country country : countries){
        countryMap.put(country, country.getCountryName());
    }

    model.addAttribute("countries", countryMap);
Run Code Online (Sandbox Code Playgroud)

尝试 1 个 JSP

<tr>
    <td>Country:</td>
    <td><form:select path="country">
    <form:options items="${countries}" />
    </form:select>
    </td>
</tr>
Run Code Online (Sandbox Code Playgroud)

尝试 2JAVA

List<Country> countries= countryService.getAllCountry();
    model.addAttribute("countries", countries);
Run Code Online (Sandbox Code Playgroud)

尝试2个 JSP

<tr>
    <td>Country:</td>
    <td><form:select path="country" id="country">
        <form:options items="${countries}" itemValue="country" itemLabel="countryName" />
    </form:select>
</tr>
Run Code Online (Sandbox Code Playgroud)

我可以正确填充下拉菜单,但当我尝试保存它时,似乎是在尝试保存字符串值而不是对象值。我正在使用 POST 请求来保存页面

有谁知道如何做到这一点?

小智 5

对于这些情况,我就是这样做的:

爪哇

List<Country> countries= countryService.getAllCountry();
model.addAttribute("countries", countries);
Run Code Online (Sandbox Code Playgroud)

联合应用程序

<select name="idCountry">   
<c:forEach items="${countries}" var="country">
<option value="${country.id}">${contry.countryName}</option> 
</c:forEach>
Run Code Online (Sandbox Code Playgroud)

后爪哇

Country c = CountryRepositroy.findById();
Adresse.setCountry(c);
Run Code Online (Sandbox Code Playgroud)