Thymeleaf turns variable as '*{id}'

Viewed 16

This is my update method for updating an owner. But I am getting an error Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long' because it doesn't gives me the Long value.

  public Owner updateOwner(Long id, OwnerDTO ownerDTO){
        Optional<Owner> byId= ownerRepository.findById(id);
        if(!byId.isPresent()){
            return null;
        }
        Owner updatedOwner = byId.get();
        if(!StringUtils.isEmpty(ownerDTO.getPhoneNumber())){
            updatedOwner.setPhoneNumber(ownerDTO.getPhoneNumber());
        }
        if(!StringUtils.isEmpty(ownerDTO.getMail())){
            updatedOwner.setMail(ownerDTO.getMail());
        }
        if(!StringUtils.isEmpty(ownerDTO.getFirstName())){
            updatedOwner.setFirstName(ownerDTO.getFirstName());
        }
        if(!StringUtils.isEmpty(ownerDTO.getLastName())){
            updatedOwner.setLastName(ownerDTO.getLastName());
        }

        return ownerRepository.save(updatedOwner);
    }

This is my html

 <h2>Update Owner</h2>
    <hr/>
    <form th:action="@{/api/v1/owners/updateOwnerForm/*{owner.id}}" th:object="${owner}" method="put">
        <input name="_method" type="hidden" value="put" />

        <input type="text" th:field="*{firstName}" placeholder="Enter name" class="form-control col-4 mb-4" />

        <input type="text" th:field="*{lastName}" placeholder="Enter surname" class="form-control col-4 mb-4" />

        <input type="text" th:field="*{phoneNumber}" placeholder="Enter phone number" class="form-control col-4 mb-4" />

        <input type="text" th:field="*{mail}" placeholder="Enter salary" class="form-control col-4 mb-4" />


        <button th:href="@{/api/v1/owners/showList}" class="btn btn-primary col-2" type="submit">Update</button>

    </form>
    <hr/>
    <a th:href="@{/api/v1/owners/showList}">Back to list</a>
</div>
</body>
</html>

The owner.id part doesn't appears as Long instead it appears as {owner.id}

How to solve this issue? Any ideas?

2 Answers

I found the solution while trying things. Adding a + sign between url and *{owner.id} did it for me!

Change:

<form th:action="@{/api/v1/owners/updateOwnerForm/*{owner.id}}"

to:

<form th:action="@{/api/v1/owners/updateOwnerForm/{id}(id=${owner.id})}"

See String concatenation with Thymeleaf for more info.

Related