java - 如何从 thymeleaf 检索输入文本?

标签 java spring-boot thymeleaf

我正在尝试从 thymeleaf 输入中获取一个值到我的 java 类中。

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>

如何将输入的文本检索到我的 java 类中?

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";
}

我能够运行我的应用程序并查看 thymeleaf View 。当我在文本框中输入一些文本并点击提交时。我收到一个错误。

错误消息

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

我的应用程序是使用 Springboot、Java 和 Thymeleaf 创建的。我究竟做错了什么? ModelandView 是否有可能无法与 PostMapping 一起使用?我也关注了https://spring.io/guides/gs/handling-form-submission/我让该示例正常工作,但是当我尝试遵循逻辑并将其实现到我的项目中时。它不起作用。

最佳答案

在 HTML 中,将 th:action="@{index}" 更改为 th:action="@{/index}"。这将使 Thymeleaf 能够正确解决它。

关于java - 如何从 thymeleaf 检索输入文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40934668/

相关文章:

java - Java中从字符串中提取整数并将它们相加

具有基于映射的属性的 Spring-boot ConditionalOnProperty

Spring 启动+ thymeleaf : get logged in user

java - thymeleaf :if expression not evaluating true

java - 通过 JMX 监控我的 jsp-servlet 应用程序

Java Swing 错误 =S AbsoluteConstraints

java - 有没有一种聪明的方法来检查哈希表中的每个键是否都具有相同的值?

java - MySQL中如何处理锁定帐户

java - 忽略属性占位符 - Spring Boot

html - 使用 Thymeleaf 将 CSS 链接到 HTML View