我有一个游戏和开发人员。游戏中有一组开发人员。我想创建一个表单,我可以将游戏添加到数据库中。在表单中输入名称,价格并检查开发人员。所以我为每个开发人员创建一个复选框。但是,当我检查那些页面似乎刷新。当我调试它似乎我的控制器永远不会到达doSubmitAction函数。当我遗漏复选框时,一切都按预期工作。 春天无法创造收藏品吗?我不完全理解Spring背后发生的事情。这是我用spring创建的第一个项目。
这是我的表格:
<form:form method="POST" commandName="game" >
<table>
<tr>
<td>
Name
</td>
<td>
<form:input path="gameNaam" size="20" />
</td>
</tr>
<tr>
<td>Choose Developers</td>
<td>
<form:checkboxes id="selectdeveloper" items="${developers}" path="developers" itemLabel="naam" />
</td>
</tr>
<tr>
<td>
Price
</td>
<td>
<form:input path="prijs" size="10" />
</td>
</tr>
<tr>
<td>
<input type="submit" value="Add" />
</td>
<td></td>
</tr>
</table>
</form:form>
formController:
public class GameFormController extends SimpleFormController {
private GameOrganizer gameOrganizer;
public GameFormController() {
setCommandClass(Game.class);
setCommandName("game");
setFormView("AddGame");
setSuccessView("forward:/Gamedatabase.htm");
}
public void setGameOrganizer(GameOrganizer gameOrganizer){
this.gameOrganizer=gameOrganizer;
}
@Override
protected Object formBackingObject(HttpServletRequest request) throws Exception {
Game game = null;
long id = ServletRequestUtils.getLongParameter(request, "id");
if(id<=0){
game = new Game();
}else{
game = gameOrganizer.getGame(id);
}
return game;
}
@Override
protected void doSubmitAction(Object command) throws Exception {
Game game = (Game) command;
if(game.getId()<=0){
gameOrganizer.addGame(game);
}else{
gameOrganizer.update(game);
}
}
@Override
protected Map referenceData(HttpServletRequest request) throws Exception {
Set<Developer> developers = gameOrganizer.getAllDevelopers();
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("developers", developers);
return map;
}
}
答案 0 :(得分:1)
好的,显然我必须为Developer制作一个propertyEditor。 这个网站有一个很好的解释:
http://static.springsource.org/spring/docs/2.0.x/reference/validation.html
编辑额外信息:
所以当你勾选一个复选框时,它会给你一个字符串值。 当然,收藏必须用开发者对象制作。
所以我创建了一个developerEditor:
package domainmodel;
import java.beans.PropertyEditorSupport;
public class DeveloperEditor extends PropertyEditorSupport {
private GameOrganizer gameOrganizer;
public void setGameOrganizer(GameOrganizer gameOrganizer) {
this.gameOrganizer = gameOrganizer;
}
@Override
public void setAsText(String id) {
long id2 = Long.parseLong(id);
Developer type = gameOrganizer.getDeveloper(id2);
setValue(type);
}
}
使用复选框我作为itemvalue给出了对象的id
<form:checkboxes id="selectdeveloper" items="${allDevelopers}" itemValue="id" path="developers" itemLabel="name" />
然后在formcontroller中我重写initBinder方法。 因此,当我必须填写开发人员对象时,它将首先使用我的编辑器将其从字符串转换为开发人员对象。
private DeveloperEditor developerEditor;
public void setDeveloperEditor(DeveloperEditor developerEditor){
this.developerEditor = developerEditor;
developerEditor.setGameOrganizer(gameOrganizer);
}
@Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
binder.registerCustomEditor(Developer.class, developerEditor);
}
那就是人们。 如果有人有任何问题,我很乐意回答。