Reputation:
I am implementing contact form with Spring Boot MVC and Thymeleaf.
I receive this error and exception, when open /message
:
ERROR 8766 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/message.html]")] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'msg' available as request attribute
My controller:
@GetMapping("/message")
public String message() {
return "message";
}
@PostMapping("/message")
public String sendMessage(@ModelAttribute(name = "msg") Message msg, Model model, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "main";
}
model.addAttribute("msg", msg);
mailService.sendMessage(msg.getTitle(), msg.getMessage());
return "message";
}
message.html:
<form action="/message" th:action="@{/message}" th:object="${msg}" method="post">
<p>
<label>Title:
<input type="text" th:field="${msg.title}"/>
</label>
</p>
<p>
<label>Message:
<input type="text" th:field="${msg.message}"/>
</label>
</p>
<p>
<input type="submit" value="Submit"/>
<input type="reset" value="Reset"/>
</p>
</form>
What is my mistake?
On the /message
page error:
There was an unexpected error (type=Internal Server Error, status=500).
An error happened during template parsing (template: "class path resource [templates/message.html]")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/message.html]")
Upvotes: 0
Views: 80
Reputation: 396
This
model.addAttribute("msg", msg);
should be in your GetMapping, not where you have in the PostMapping. You Bind the Message object to the form in order to view the form;
@GetMapping("/message")
public String message(Model model) {
model.addAttribute("msg", new Message());
return "message";
}
Upvotes: 2