2016-08-31 175 views
0

是否可以通過使用select標籤將對象(汽車)傳遞給我的控制器?當我嘗試使用下面的代碼,車子參數沒有被認可,它的結果是:如何在控制器中將對象傳遞給ModelAttribute - Spring

400錯誤的請求

一個car由2串(品牌,型號) 一個spot由1號車和2個字符串(鎮,streetName)

我的JSP頁面:

<form:form method="post" modelAttribute="spot" action="${post_url}">   
    <form:select path="car"> 
     <form:option value="-" label="--Select car"/> 
     <form:options items="${cars}"/> 
    </form:select> 

    <form:input type="text" path="town"/>   
    <form:input type="text" path="streetName"/>    
    <button>Save</button> 
</form:form> 

我對照奧勒:

@RequestMapping(value="/addSpot", method = RequestMethod.POST) 
public String save(@ModelAttribute("spot") Spot spot){ 
    service.addSpotToService(spot);  
    return "redirect:/spots.htm"; 
} 

回答

1

可以克里特組件到汽車的長ID轉換爲對象車

@Component 
public class CarEditor extends PropertyEditorSupport { 

    private @Autowired CarService carService; 

    // Converts a Long to a Car 
    @Override 
    public void setAsText(Long id) { 
     Car c = this.carService.findById(id); 

     this.setValue(c); 
    } 

} 
在控制器

添加此

private @Autowired CarEditor carEditor; 

    @InitBinder 
    public void initBinder(WebDataBinder binder) { 
     binder.registerCustomEditor(Car.class, this.carEditor); 
    } 

,然後通過汽車的id在選擇

<form:select path="car"> 
     <form:option value="-" label="--Select car"/> 
     <form:options items="${cars}" itemValue="id" itemLabel="model"/> 
    </form:select> 

看看在彈簧文檔http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/view.html和特別在節的選項標籤

的項目屬性通常與一個集合或項目對象數組 填充。 itemValue和itemLabel只需引用這些項目對象的bean 屬性(如果指定的話);否則,項目 對象本身將被串接。或者,您可以指定 a項目的地圖,在這種情況下,地圖關鍵字將被解釋爲選項 值,地圖值對應於選項標籤。如果itemValue 和/或itemLabel恰巧也被指定,則項目值 屬性將應用於地圖項,而項目標籤屬性 將應用於地圖值。

讓我知道這是否爲你工作

+0

當我實現這一點,我得到一個錯誤,而加載JSP中bean類汽車的財產「車」是無效的。可能是因爲中的路徑設置爲「car」 – denelias

+0

Class Car是否有ID? –

+0

是的,私人長ID – denelias

相關問題