簡體   English   中英

如何將對象傳遞給控制器​​中的ModelAttribute-Spring

[英]How to pass Object to ModelAttribute in controller - Spring

是否可以通過使用選擇標簽將對象(汽車)傳遞到控制器? 當我嘗試使用以下代碼時,無法識別car參數,其結果是:

400錯誤的要求

一輛car由2根弦(品牌,型號)組成。一個spot由1輛汽車和2根弦(城鎮,街道名稱)組成

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

您可以創建一個組件以將Car的Long ID轉換為對象car

@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> 

請查看spring文檔http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/view.html ,特別是在options標簽部分

items屬性通常填充有item對象的集合或數組。 如果已指定,則itemValue和itemLabel只是引用那些item對象的bean屬性; 否則,item對象本身將被字符串化。 或者,您可以指定項目映射,在這種情況下,映射鍵將解釋為選項值,並且映射值對應於選項標簽。 如果恰好同時指定了itemValue和/或itemLabel,則item value屬性將應用於地圖鍵,item label屬性將應用於地圖值。

讓我知道這是否對您有用

暫無
暫無

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

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