簡體   English   中英

SPRING MVC:如何將單擊的單選按鈕值傳遞給 controller?

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

我正在使用 Spring MVC controller。

是否可以在單選按鈕的路徑值中設置 object?

在我的 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>

還有我的 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;
}

這是我的地址表

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;
}
}

我想從我的 controller 中檢索選定的 object 地址,但我有一個錯誤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 或代碼恢復地址,因為您已經有了列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM