java - 如何在 Thymeleaf/HTML 中使用带有 Java + Spring 的复选框?

标签 java spring spring-boot checkbox thymeleaf

我如何使用 Thymeleaf 从 html 中的复选框接收到 true 或 false 到我的 Controller ,以便我可以获取 true 或 false 的值并保存在我的数据库中。到目前为止,我收到了这些错误:

  1. org.thymeleaf.exceptions.TemplateInputException:
    An error happened during template parsing (template: "class path resource [templates/normal/start-dag.html]")
  2. Caused by: org.attoparser.ParseException:
    Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputCheckboxFieldTagProcessor' (template: "normal/start-dag" - line 24, col 44)
  3. Caused by: org.thymeleaf.exceptions.TemplateProcessingException:
    Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputCheckboxFieldTagProcessor' (template: "normal/start-dag" - line 24, col 44)
  4. 2018-07-17 09:05:16.097 ERROR 6713 --- [nio-8080-exec-2] 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/normal/start-dag.html]")] with root cause
  5. java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'goodNightOfSleep' available as request attribute
    at org.springframework.web.servlet.support.BindStatus.(BindStatus.java:153) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:903) ~[spring-webmvc-5.0.7.RELEASE.jar:5.0.7.RELEASE]

My html looks like this:

<table>
    <tr>
        <input type="checkbox" th:path="goodNightOfSleep">
        <label th:for="${#ids.next('goodNightOfSleep')}" th:text="#{StartDay.goodNightOfSleep}">Kan du huske hvad du drømte?</label>
        <input type="checkbox" th:field="*{goodNightOfSleep}"/>
    </tr>
</table>

还有我的 Controller :

// Start Day
@GetMapping("/normal/start-dag")
public  String opretGoal() {
    return "normal/start-dag";
}

@PostMapping("/normal/start-dag")
public String opretGoal(@ModelAttribute StartDay startDay, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return "/normal/menu";
    }
    startDayService.createGoalOfTheDay(startDay);

    return "normal/menu";
}

我的 StartDay.java 类:

@Entity
@Table(name = "start_day")
public class StartDay {

    @Id
    @Column(name = "age_in_days", nullable = true)
    private int ageInDays;
    @Column(name = "day_created", nullable = true)
    private String dayCreated;
    @Column(name = "username", nullable = true)
    private String username;
    @Column(name = "dream_remembered", nullable = true)
    private boolean dreamRemembered;
    @Column(name = "nightmare", nullable = true)
    private boolean nightmare;
    @Column(name = "waking_time", nullable = true)
    private int wakingTime;
    @Column(name = "good_night_of_sleep", nullable = true)
    private boolean goodNightOfSleep;

感谢任何帮助:)

更新#1

所以我只是试图从 html 中移动第二个 th:field,所以它看起来像这样:

<table>
    <tr>
        <input type="checkbox" th:path="goodNightOfSleep">
        <label th:for="${#ids.next('goodNightOfSleep')}" th:text="#{StartDay.goodNightOfSleep}">Kan du huske hvad du drømte?</label>
    </tr>
</table>

这让我实际上能够登陆页面,但我的复选框看起来像这样,并且没有返回值:enter image description here

最佳答案

Controller 方法:

@GetMapping("/normal/start-dag")
public String opretGoal(Model model) {
    ...
    StartDay startDay = .... // e.g. new StartDay();
    model.addAttribute("startDay", startDay);
    ...
    return "normal/start-dag";
}

@PostMapping("/normal/start-dag")
public String opretGoal(@Valid StartDay startDay, BindingResult bindingResult, Model model)
{
    if (bindingResult.hasErrors()) {
        // log and/or handle errors
    }
    else {
        // your logic goes here
        startDayService.createGoalOfTheDay(startDay);
    }
    return "/normal/menu";
}

模板片段:

<form action="... or use th:action" method="post" th:object="${startDay}">
    ...
    <input type="checkbox" name="goodNightOfSleep">
    ...
</form>

您也可以将 th:field 用于 goodNightOfSleep-Input,但它的工作方式与上面所写的一样。 Thymeleaf 按名称将字段与表单元素中定义的对象匹配。如果您选中该框,则该值将为真,否则将为假。

要点是 1.) 将对象添加到模型和 2.) 接收对象作为输入参数。

警告:代码是在没有测试的情况下写入编辑器的。可能有错别字。

关于java - 如何在 Thymeleaf/HTML 中使用带有 Java + Spring 的复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51375414/

相关文章:

spring-boot - 在同一台服务器上运行服务器 Spring Boot 应用程序

java - 当我添加最新的 <dependency> 时,Spring Boot Maven 项目不会下载最新的 Oracle ojdbc8 .jar 文件

java - JDBC 连接失败 : java. sql.SQLException: Communication link failure: Bad handshake

java - Flyway 可重复迁移 - 不在 Spring boot 中执行

spring - 无法从 tomcat 的 lib 文件夹访问自定义 jar

spring-boot - 获取错误 : No qualifying bean of type org. springframework.boot.info.BuildProperties

java - 如何在 Java 中访问 Perl 变量?

java - 如何知道你的算法是否是 O(n2)?

java - Spring 安全: Authentication with Database

java - 插件 spring-boot-maven-plugin' 的错误解析版本