You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Thymeleaf模板处理异常:高校IT工单系统数据不保存不显示

问题排查与修复方案

一、控制器请求映射冲突(核心问题)

你的TicketController中存在两个同路径的@PostMapping("/ticket/new")方法,这会导致Spring无法正确路由请求:

  1. 访问新建工单页面应为GET请求,将处理表单模型的方法改为@GetMapping,并直接返回表单页面:
@GetMapping("/ticket/new")
public String newForm(Model model){
    model.addAttribute("ticket", new Ticket());
    model.addAttribute("isNew", true);
    model.addAttribute("authors", service.getAuthors());
    return "ticket/new";
}
  1. 保留处理表单提交的@PostMapping方法,确保路径唯一:
@PostMapping("/ticket/new")
public String post(Ticket ticket) throws IOException {
    service.save(ticket);
    return "redirect:/index";
}

二、Thymeleaf模板绑定错误

1. /ticket/new.html表单绑定问题

  • th:object错误:使用控制器传入的模型变量名${ticket}而非全类名:
<form method="post" th:action="@{/ticket/new}" th:object="${ticket}">
  • Status下拉框枚举绑定错误:直接使用枚举实例${status},而非values():
<select id="status" th:field="*{status}">
    <option th:each="status : ${T(ch.supsi.webapp.web.model.Status).values()}" 
            th:value="${status}" 
            th:text="${status}"></option>
</select>
  • Type下拉框枚举方法错误:values需加括号values():
<select id="type" th:field="*{type}">
    <option th:each="type : ${T(ch.supsi.webapp.web.model.Type).values()}" 
            th:value="${type}" 
            th:text="${type}">Bug</option>
</select>
  • Author字段绑定错误:Author是实体类,改为下拉框选择现有作者:
<div>
    <label for="author">Author:</label>
    <select id="author" class="form-select" th:field="*{author}">
        <option th:each="author : ${authors}" 
                th:value="${author.id}" 
                th:text="${author.name}"></option>
    </select>
</div>
  • Home链接路径错误:修改为控制器路由路径:
<a th:href="@{/index}">Home</a> |

2. index.html页面问题

  • 重复<html>标签:合并为一个并保留Thymeleaf命名空间:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
  • 静态链接改为Thymeleaf路由:避免直接访问静态HTML文件,走控制器映射:
<div class="item"> <a th:href="@{/index}">Home</a></div>

三、其他潜在问题

  1. Ticket实体日期字段:确保date字段有默认值或通过@CreatedDate配合JPA Auditing自动填充,避免Thymeleaf渲染报错。
  2. Author实体绑定:确保Author类实现toString()方法,或在下拉框中明确绑定id与显示字段,避免表单提交时实体转换失败。

内容的提问来源于stack exchange,提问作者starcat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 00:44:56