Jackie Jackie - 9 days ago 10
Java Question

How to get inputs from thymeleaf without Ambigous Handler error?

I am trying to get a value from thymeleaf input into my java class.

Simple script from thymeleaf

<h1>Form</h1>
<form action="#" th:action="@{/index}" th:object="${emails}" method="post">
<p>Enter Emails: <input type="text" th:field="*{email}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>


How would I be able to retrieve emails into my java class?

Controller

@Controller
@RequestMapping(method = RequestMethod.GET)
public class IndexController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView getdata() throws IOException {
ModelAndView model = new ModelAndView("index");
model.addObject("emails", new MailModel());
return model;
}

@PostMapping("/")
public String emailSumbit(@ModelAttribute MailModel emails) {
System.out.println(emails.getEmail());

return "/";
}


Error Message

Ambiguous handler methods mapped for HTTP path 'http://localhost:8080/': {public org.springframework.web.servlet.ModelAndView com.spring.web.controller.IndexController.getdata() throws java.io.IOException, public java.lang.String com.spring.web.controller.IndexController.emailSumbit(com.spring.web.model.MailModel)}


My Application is created with Springboot, Java, and Thymeleaf. What am I doing wrong? Is it possible that ModelandView does not work with PostMapping? I also followed https://spring.io/guides/gs/handling-form-submission/ and I got that sample working, but when I tried to follow the logic and implement into my project. It did not work.

Answer

Before declaring your controller, you are setting the RequestMethod to GET everywhere. On the methods you are setting them again, which is ambigous.

Remove the @RequestMapping(method = RequestMethod.GET) in line 2. This should fix the mentioned problem.