0

Приложение не может найти объект соответствующий атрибуту, указанному в форме. Я новичек. Буду благодарен!

Контроллер:

    @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"));
    model.addAttribute("platforms", platforms);
    model.addAttribute("ad",ad);
    return "ad-edit";
}

@PostMapping("/ads/{id}/edit")
public String adUpdate(@PathVariable(value = "id") int id, @RequestBody 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.platformsIds)));
    ad.setName(adDto.getName());
    ad.setAssetUrl(adDto.getAssetUrl());
    adRepository.save(ad);
    return "redirect:/ads";
}

ДТО:

public class AdDTO {
public int id;
public String name;
public String assetUrl;
public Status status;
public Campaign campaign;
public Set<Integer> platformsIds;

HTML:

<!DOCTYPE html>
<html>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
      integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<link rel="stylesheet" href="/css/style.css"/>
<head>
    <meta charset="UTF-8">
    <title>Редактирование обьявления</title>
</head>
<body>
<header>
    <nav class="navbar navbar-light bg-light">
        <form class="container justify-content-start">
            <h3 class="caption">Редактирование обьявления <span th:text="${ad.name}"></span></h3>
            <button class="navbar-toggler" type="button">
                <a href="../home.html" th:href="@{/home}">На главную</a></button>
            <button type="button" class="btn btn-light">
                <a href="../info.html" th:href="@{/info}">Обе SQL Таблицы</a></button>
            <button type="button" class="btn btn-light">
                <a href="../ads.html" th:href="@{/ads}">Обьявления</a></button>
            <button type="button" class="btn btn-light">
                <a class="link" href="../campaigns.html" th:href="@{/campaigns}">Кампании</a></button>
        </form>
    </nav>
</header>
<!--<div th:object="${adDto}"  class="container justify-content-start">-->
    <form th:object="${adDto}" th:action="@{/ads/{id}/edit}" method="post">
        <input type="text" th:value="${ad.name}" th:field="*{adDto.name}"

               placeholder="Введите название обьявления" class="form-control">

        <input type="text" th:value="${ad.assetUrl}" th:field="*{adDto.assetUrl}"

               placeholder="Введите ссылку на рекламу" class="form-control">
        <!--        <h6>id кампании </h6> <h6 th:value="${el.campaign.id}"></h6>-->
        <select class="form-control" th:field="*{adDto.platformsIds}" multiple="multiple">
            <div> <option th:each="platform : ${platforms}"
                    th:value="${platform.id}"
                    th:text="${platform.name}"
                    th:selected="${adDto.platformsIds.contains(platform.id)}">
            </option> </div>
        </select>
        <button type="submit" class="btn btn-success">Редактировать</button>
    </form>
<!--</div>-->
</body>
</html>

введите сюда описание изображения

1 ответ 1

0

@RequestBody применяеться при использовании @RestController со Spring для постороения REST API. При использовании Thymeleaf, нужно брать @Controller и применить @ModelAttribute.

В @GetMapping методе, нужно добавить экземпляр AdDTO, созданный из Ad обьекта, что-то вроде этого:

@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"));
    model.addAttribute("platforms", platforms);
    model.addAttribute("adDto", mapToDto(ad)); // <-- changed line here
    return "ad-edit";
}

For the @PostMapping, use @ModelAttribute:

@PostMapping("/ads/{id}/edit")
public String adUpdate(@PathVariable(value = "id") int id, @ModelAttribute("adDto") 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.platformsIds)));
    ad.setName(adDto.getName());
    ad.setAssetUrl(adDto.getAssetUrl());
    adRepository.save(ad);
    return "redirect:/ads";
}
0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.