SPRING MVC:如何将单击的单选按钮值传递给控制器​​?

SPRING MVC : How to pass the radio button value which is clicked to controller?

我正在使用 Spring MVC 控制器。

是否可以在单选按钮的路径值中设置对象?

在我的表格下方 jsp

<spring:url value="/update" var="update" htmlEscape="false"/>
<form:form action="${update}" method="post" modelAttribute="addressForm">
     <c:forEach items="${addresses}" var="address">
     <form:radiobutton path="address" value="${address}" label="${address.city}"/>
     </c:forEach>
         <input type="submit" value="Confirm"/>
</form:form>

还有我的控制器

@RequestMapping(value = "/update", method = RequestMethod.POST)
public String chooseAddress(@Valid final AddressForm form, final BindingResult bindingResult,
                                         final RedirectAttributes redirectAttributes){
    if (bindingResult.hasErrors()){
        System.out.println("Erros");
    }else{
        System.out.println("NO Erros");
    }

    return REDIRECT_URL;
}

这是我的地址表

public class AddressForm implements Serializable {

private static final long serialVersionUID = 3734278553292263688L;

@NotNull
AddressDTO address;

public AddressDTO getAddress() {
    return address;
}

public void setAddress(AddressDTO address) {
    this.address = address;
}
}

我想从我的控制器中检索选定的对象地址,但我有一个错误 bindingResult.hasErrors() return true 有以下错误和地址为 null

的表单
   org.springframework.validation.BeanPropertyBindingResult: 1 errors
   Field error in object 'addressForm' on field 'address': rejected 
   value []; codes 
[typeMismatch.AddressForm.address,typeMismatch.address,typeMismatch.com.data.AddressDTO,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [AddressForm.address,address]; arguments []; default message [address]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.data.AddressDTO' for property 'address'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.data.AddressDTO' for property 'address': no matching editors or conversion strategy found]

我建议你像这样在路径中传递地址 id :

<spring:url value="/update" var="update" htmlEscape="false"/>
<form:form action="${update}" method="post" modelAttribute="addressForm">
 <c:forEach items="${addresses}" var="address">
 <form:radiobutton path="id"label="${address.city}"/>
 </c:forEach>
     <input type="submit" value="Confirm"/>
</form:form>

public class AddressForm implements Serializable {

private static final long serialVersionUID = 3734278553292263688L;

@NotNull
String id;

public String getId() {
  return id;
}

public void setId(String id) {
   this.id = id;
}
}

由于您已经有了列表,因此您可以通过 ID 或代码恢复地址。