我想在Spring启动应用程序中使用类型转换器并使用Thymeleaf,但我无法使它工作。我在Github上放了一些代码,这样你就可以看到我正在尝试做什么。这是Spring 1.5.1和Thymeleaf 3.0.3。 https://github.com/matthewsommer/spring-thymeleaf-simple-converterSpring + Thymeleaf类型转换器的形式
基本上这段代码只是试图添加一个人到评论对象。 person对象在发布时为null,我不明白为什么。
奇怪的是,人的ID没有被添加到value属性中,但是如果删除了th:field =“* {body}”。我认为它必须做这个:https://github.com/thymeleaf/thymeleaf/issues/495但我目前正试图增加BindingResult和它不工作...
我的HTML是:
<body>
<div th:if="${personObject != null}" th:text="${personObject.name}"></div>
<form th:action="@{/}" th:object="${comment}" method="post">
<input type="hidden" th:if="${personObject != null}" th:value="${personObject.id}" th:field="*{person}" />
<textarea id="comment" placeholder="Comment..." th:field="*{body}"></textarea>
<button id="comment_submit" type="submit">Comment</button>
</form>
<div th:text="${comment.body}"></div>
</body>
我的控制器:
@Controller
public class HomeWebController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String getHome(final HttpServletRequest request, final Map<String, Object> model, @ModelAttribute(value = "comment") Comment comment) {
model.put("personObject", new Person(1, "John Smith"));
return "Home";
}
@RequestMapping(value = "/", method = RequestMethod.POST)
public String postHome(final HttpServletRequest request, final Map<String, Object> model, @ModelAttribute(value = "comment") Comment comment) {
model.put("commentBody", comment.getBody());
model.put("person", comment.getPerson());
return "Home";
}
}
和转换器:终于
@Component
public class StringToPersonConverter implements Converter<String, Person> {
@Autowired
public StringToPersonConverter() { }
@Override
public Person convert(String id) {
if(id == "1") {
Person person = new Person(1, "John Smith");
return person;
}
return null;
}
}
您是否试过该代码? – cralfaro