好的,所以我已经构建了一个转换器并将其添加到调度程序 xml。但它不会起作用。我不明白控制器应该如何知道何时应该使用转换器。在我的 jsp 页面中,我检查了乘法复选框。每个复选框都包含一个开发人员的 ID。Spring 应该从这些 id 中创建一组开发人员。我觉得我在控制器中遗漏了一些东西。我以前用编辑器来做,然后你会覆盖 initbinder 方法。我不知道如何使用转换器来做到这一点。
提前谢谢你,大卫
所以首先我做了一个实现接口的类:
public class DeveloperConverter implements Converter<String, Developer> {
private GameOrganizer gameOrganizer;
public void setGameOrganizer(GameOrganizer gameOrganizer) {
this.gameOrganizer = gameOrganizer;
}
public Developer convert(String s) {
long id2 = Long.parseLong(s);
Developer type = gameOrganizer.getDeveloper(id2);
return type;
}
}
然后我将 bean 添加到调度程序 xml:
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="converters.GameConverter" />
<bean class="converters.DeveloperConverter" />
</list>
</property>
</bean>
和控制器:
@Controller
@RequestMapping("/AddGame")
public class GameFormController {
@Autowired
private GameOrganizer gameOrganizer;
private DeveloperConverter developerEditor;
private GameValidator gameValidator;
private ConversionService service;
public GameFormController() {
setGameValidator(new GameValidator());
}
public void setGameOrganizer(GameOrganizer gameOrganizer) {
this.gameOrganizer = gameOrganizer;
}
public void setDeveloperEditor(DeveloperConverter developerEditor) {
this.developerEditor = developerEditor;
developerEditor.setGameOrganizer(gameOrganizer);
}
public void setGameValidator(GameValidator gameValidator) {
this.gameValidator = gameValidator;
}
@RequestMapping(method = RequestMethod.GET)
private String showForm(ModelMap model) {
return "AddGame";
}
@ModelAttribute("editGame")
private Game GameformBackingObject(HttpServletRequest request) throws Exception {
Game game = null;
long id = ServletRequestUtils.getLongParameter(request, "id");
if (id <= 0) {
game = new Game();
} else {
game = new Game();
game.setId(gameOrganizer.getGame(id).getId());
game.setDevelopers(gameOrganizer.getGame(id).getDevelopers());
game.setGameNaam(gameOrganizer.getGame(id).getGameNaam());
game.setImages(gameOrganizer.getGame(id).getImages());
game.setPrijs(gameOrganizer.getGame(id).getPrijs());
}
return game;
}
@RequestMapping(method = RequestMethod.POST)
protected String doSubmitAction(@ModelAttribute("editGame") Game game, BindingResult result) throws Exception {
gameValidator.validate(game, result);
if (result.hasErrors()) {
return "AddGame";
} else {
if (game.getId() <= 0) {
gameOrganizer.addGame(game);
} else {
gameOrganizer.update(game);
}
return "forward:/Gamedatabase.htm";
}
}
@ModelAttribute("allDevelopers")
private Set<Developer> getDevelopers() throws Exception {
Set<Developer> developers = gameOrganizer.getAllDevelopers();
return developers;
}
@ModelAttribute("currentId")
private long getCurrentId(HttpServletRequest request) throws ServletRequestBindingException {
long id = ServletRequestUtils.getLongParameter(request, "id");
return id;
}
}