我正在学习Spring / Thymeleaf,我正在建立一个小项目。 这是我的一段代码: 这是我的控制器:
@Controller
public class MovieController {
private IMovieService movieService;
private IGenreService genreService;
@Autowired
public MovieController(IMovieService movieService, IGenreService genreService) {
this.movieService = movieService;
this.genreService = genreService;
}
@InitBinder(value = "genres")
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Genre.class, new GenrePropertyEditor());
}
@RequestMapping(value = "/addNewMovie", method = RequestMethod.GET)
public String addMovieForm(Model model) {
model.addAttribute("movie", new Movie());
model.addAttribute("genreList", genreService.findAll());
return "movie-add/view";
}
@RequestMapping(value = "/addNewMovie", method = RequestMethod.POST)
public String addMovie(@ModelAttribute Movie movie, Model model) {
movieService.save(movie);
return "redirect:allMovies";
}
}
这是我的编辑:
public class GenrePropertyEditor extends PropertyEditorSupport {
@Autowired
private GenreService genreService;
@Override
public void setAsText(String id) {
final Genre part = genreService.findById(UUID.fromString(id));
setValue(part);
}
@Override
public String getAsText() {
return ((Genre) getValue()).getId().toString();
}
}
这是我的观点:
<form action="#" th:action="@{/addNewMovie}" th:object="${movie}"
method="post">
<p>
Title : <input type="text" th:field="*{title}" />
</p>
<p>
Description : <input type="text" th:field="*{description}" />
</p>
<p>
Year : <input type="text" th:field="*{year}" />
</p>
<select class="form-control" th:field="*{genres}" multiple="multiple">
<option th:each="genre : ${genreList}"
th:field="*{genres}"
th:value="${genre.id}"
th:text="${genre.genreInformation}">
Action
</option>
</select>
<p>
<input type="submit" value="Submit" /> <input type="reset"
value="Reset" />
</p>
</form>
当我调用addMovie方法时,它会创建一个新电影。标题,描述和年份,但没有流派。我调试它,我发现: 1当我提交两种类型时。它创建一个包含两个空值的List。 2未调用Init Binder方法。
答案 0 :(得分:0)
您是否尝试从
更改 @InitBinder(value = "genres")
到
@InitBinder
我认为由于对#34;类型&#34;的限制,该方法不是通话。