【问题标题】:How to retrieve input text from thymeleaf?如何从百里香中检索输入文本?
【发布时间】:2017-04-17 12:13:35
【问题描述】:

我正在尝试从 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
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 视图。当我在文本框中输入一些文本并点击提交时。我收到一个错误。

错误信息

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/,并且我得到了那个示例,但是当我尝试遵循逻辑并在我的项目中实施时。它没有用。

【问题讨论】:

  • 我的 POJO 只包含私人字符串电子邮件; //getter 和 setter
  • 您可以尝试根据本教程更改控制器:spring.io/guides/gs/validating-form-input。所以代替emailSubmit(@ModelAttribute MailModel emails)试试emailSubmit(MailModel emails, BindingResult bindingResult)

标签: java spring-boot thymeleaf


【解决方案1】:

在您的 HTML 中,将 th:action="@{index}" 更改为 th:action="@{/index}"。这将允许 Thymeleaf 正确解决它。

【讨论】:

    猜你喜欢
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2015-04-13
    相关资源
    最近更新 更多