2017-02-13 4 views
0

Я пытаюсь использовать конвертер типов в приложении Spring Boot и использовать Thymeleaf, но я не могу заставить его работать. Я поместил некоторый код в Github, чтобы вы могли точно видеть, что я пытаюсь сделать. Это Spring 1.5.1 и Thymeleaf 3.0.3. https://github.com/matthewsommer/spring-thymeleaf-simple-converterПреобразователь типа Spring + Thymeleaf в форме

В основном этот код просто пытается добавить человека в объект комментария. Объект person имеет значение null, когда он отправляется, и я не понимаю, почему.

Что-то странное в том, что идентификатор человека не добавляется к атрибуту 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; 
    } 
    } 
+0

Вы пробовали код? – cralfaro

ответ

0

Привет, наконец, я должен был сделать некоторые изменения, чтобы сделать его работу, но го is является результатом класса по классам.

ConvertorApplication:

@SpringBootApplication 
@Configuration 
@EnableWebMvc 
public class ConvertorApplication extends WebMvcConfigurerAdapter { 

    public static void main(String[] args) { 
     SpringApplication.run(ConvertorApplication.class, args); 
    } 

    //Add converter and configuration annotation 
    @Override 
    public void addFormatters(FormatterRegistry registry) { 
     registry.addConverter(new StringToPersonConverter()); 
    } 
} 

StringToPersonConverter:

@Override 
public Person convert(String id) { 
    //Never compare String with == use equals, the "==" compares memory space not the values 
    if(id.equals("1")) { 
     Person person = new Person(1, "John Smith"); 
     return person; 
    } 
    return null; 
} 

HomeWebController

@Controller 
public class HomeWebController { 

    @RequestMapping(value = "/", method = RequestMethod.GET) 
    public String getHome(final Map<String, Object> model, @ModelAttribute(value = "comment") Comment comment) { 
     //Initialize the comment with the person inside, no need of personObject object 
     model.put("comment", new Comment(new Person(1, "John Smith"))); 
     return "Home"; 
    } 

    @RequestMapping(value = "/", method = RequestMethod.POST) 
    public String postHome(final Map<String, Object> model, 
          @ModelAttribute(value = "comment") Comment comment, 
          @RequestParam(value = "person.id") Person person) { 
     //from the view retrieve the value person.id which will be used by the converter to build the Person entity 
     comment.setPerson(person); 
     model.put("comment", comment); 
     return "Home"; 
    } 
} 

Комментарии (Добавить пустой конструктор)

public Comment(){} 

Person (Добавить пустой конструктор)

public Person(){} 

Home.jsp (в основном удалить personObject, не нужно)

<!DOCTYPE html> 
<html xmlns:th="//www.thymeleaf.org"> 
<body> 
    <div th:text="${comment.person.name}"></div> 
    <form th:action="@{/}" th:object="${comment}" method="post"> 
     <input type="hidden" th:field="*{person.id}" /> 
     <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> 
</html> 

Это было бы все, чтобы заставить его работать.

+0

Есть ли способ, чтобы Spring задал человеку комментарий, не делая этого в контроллере? Если вход находится в объекте формы, я чувствую, что было бы неплохо, если бы comment.person был установлен непосредственно из входов на html. – yerself

+0

Возможно, вы можете получить userId в методе GET, а затем установить User в новый комментарий и сделать его более общим, но я думаю, что более чистый способ настройки пользователя находится в методе контроллера – cralfaro

Смежные вопросы