gpt4 book ai didi

java - 如何将对象传递给 Controller ​​中的 ModelAttribute - Spring

转载 作者:行者123 更新时间:2023-12-01 09:32:54 26 4
gpt4 key购买 nike

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

400-Bad Request

一辆汽车由2个字符串组成(品牌、型号)一个地点由 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>

我的 Controller :

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

}

在你的 Controller 中添加这个

private @Autowired CarEditor carEditor;

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

然后在select中传递汽车的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特别是在选项标签

部分

The items attribute is typically populated with a collection or array of item objects. itemValue and itemLabel simply refer to bean properties of those item objects, if specified; otherwise, the item objects themselves will be stringified. Alternatively, you may specify a Map of items, in which case the map keys are interpreted as option values and the map values correspond to option labels. If itemValue and/or itemLabel happen to be specified as well, the item value property will apply to the map key and the item label property will apply to the map value.

请告诉我这是否适合您

关于java - 如何将对象传递给 Controller ​​中的 ModelAttribute - Spring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39251436/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com