2016-08-31 57 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

相关问题