Issue
I am using Spring MVC controller.
Is it possible to set an object in the path value in a radio button ?
below my form inside my 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>
And my controller
@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;
}
Here is my AddressForm
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;
}
}
I want to retrieve the selected object address from my controller but I have an Error bindingResult.hasErrors()
return true with the following error and form with address 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]
Solution
I suggest you to pass in the path the address id like that :
<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;
}
}
And you recover in your action the address by id or code since you already have list.
Answered By - CHARAFI Saad