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

SpringBoot整合Thymeleaf出现adDto请求属性不存在错误如何解决

问题修复方案

1. 修正GET接口的Model参数添加逻辑

你的Thymeleaf模板中引用了${adDto}作为表单绑定对象,但当前GET请求的adEdit方法没有将AdDTO对象存入Model,导致页面渲染时找不到对应属性抛出报错。
修改后的GET方法代码:

@GetMapping("/ads/{id}/edit")
public String adEdit(@PathVariable(value = "id") int id, Model model) {
    List<Platform> platforms = platformRepository.findAll();
    Ad ad = adRepository.findById(id).orElseThrow(() ->
            new ResponseStatusException(HttpStatus.NOT_FOUND,
                    "Ad having id " + id + " not found"));
    // 构造AdDTO对象存入Model
    AdDTO adDto = new AdDTO();
    adDto.setName(ad.getName());
    adDto.setAssetUrl(ad.getAssetUrl());
    // 提取已关联的平台id集合赋值给adDto
    adDto.setPlatformsIds(ad.getPlatforms().stream().map(Platform::getId).collect(Collectors.toSet()));
    model.addAttribute("platforms", platforms);
    model.addAttribute("ad",ad);
    model.addAttribute("adDto", adDto);
    return "ad-edit";
}

2. 修正POST接口的参数注解

@RequestBody仅用于接收JSON格式的请求体,普通表单提交的是application/x-www-form-urlencoded格式数据,需要替换为@ModelAttribute注解完成参数绑定:

@PostMapping("/ads/{id}/edit")
public String adUpdate(@PathVariable(value = "id") int id, @ModelAttribute AdDTO adDto,
                       Model model) {
    Ad ad = adRepository.findById(id).orElseThrow(() ->
            new ResponseStatusException(HttpStatus.NOT_FOUND,
                    "Ad having id " + id + " not found"));
    ad.setPlatforms(platformRepository.findAllById(adDto.getPlatformsIds()));
    ad.setName(adDto.getName());
    ad.setAssetUrl(adDto.getAssetUrl());
    adRepository.save(ad);
    return "redirect:/ads";
}

3. 修正Thymeleaf模板的绑定语法

form标签已经通过th:object="${adDto}"声明了绑定对象,后续th:field直接使用*{属性名}即可,不需要再加adDto.前缀,同时th:value可以省略,th:field会自动填充默认值,另外需要给action路径补全id参数:

<form th:object="${adDto}" th:action="@{/ads/{id}/edit(id=${id})}" method="post">
    <input type="text" th:field="*{name}"
           placeholder="Введите название обьявления" class="form-control">

    <input type="text" th:field="*{assetUrl}"
           placeholder="Введите ссылку на рекламу" class="form-control">

    <select class="form-control" th:field="*{platformsIds}" multiple="multiple">
        <option th:each="platform : ${platforms}"
                th:value="${platform.id}"
                th:text="${platform.name}">
        </option>
    </select>
    <button type="submit" class="btn btn-success">Редактировать</button>
</form>

补充注意

请确保AdDTO类已经为所有需要绑定的属性添加了Getter、Setter方法,否则Spring无法完成表单参数到DTO对象的自动赋值。


内容的提问来源于stack exchange,提问作者Денис Короленко

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 05:06:01