简体   繁体   中英

How to retrieve input text from thymeleaf?

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>Emails: <input id="emailbox" type="text" th:field="*{email}"
                      placeholder="Enter e-mails: eg; Foo@gmail.com, Bar@yahoo.com"/></p>
    <p><input type="submit" value="Submit"/> <input type="reset" value="Reset"/></p>
</form>

How would I be able to retrieve the inputted text into my java class?

Controller

@Controller
public class IndexController {

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

@PostMapping("/index")
public String emailSubmit(@ModelAttribute MailModel emails) {
    System.out.println(emails.getEmail());
    return "index";
}

I am able to run my application and see thymeleaf view. When I enter some text into the text box and hit submit. I receive an error.

Error Message

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'emails' available as request attribute

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.

In your HTML, change th:action="@{index}" to th:action="@{/index}" . This will allow Thymeleaf to resolve it properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM