如何在控制器- Spring中传递对象到模型属性



是否可以通过使用选择标签将对象(汽车)传递给我的控制器?当我尝试使用以下代码时,无法识别car参数,结果是:

400 -错误请求

A car由2个字符串(品牌,型号)组成一个spot包含1辆车和2个字符串(town, 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";
}

你可以创建一个组件来将Car的长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);
    }
然后在select 中传递car的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,特别是部分选项标签

items属性通常使用集合或数组填充项对象的。itemValue和itemLabel只是简单地引用bean这些项目对象的属性(如果指定);否则,项目对象本身将被字符串化。或者,您可以指定项的映射,在这种情况下,映射键被解释为选项值和映射值对应于选项标签。如果itemValue和/或itemLabel碰巧也指定了项值属性将应用于映射键,项目标签属性将应用于映射值

让我知道这是否适用于你

最新更新