Issue
I have this piece of code in my Thymeleaf template:
<form action="#"
th:action="@{/update/{id}(id=${user.id})}"
th:object="${user}"
method="post"
enctype="multipart/form-data">
<tr th:each="pic: ${pics}" >
<td class="col_name" >
<div class="box small">
<img th:src="'pics/' + ${user.id} + '/' + ${pic}"/>
</div>
</td>
<td class="col_actions">
<a style="color:#808080; margin-right: 10px;">
<input type="radio" th:field="*{mainPicture}" th:value="${pic}" >Main picture<br>
</a>
</td>
<td class="col_actions">
<a href="#" style="color:#808080; text-align: center;" >
<i class="fa fa-times" aria-hidden="true" ></i>
</a>
</td>
</tr>
checking the source code:
<td class="col_actions">
<a style="color:#808080; margin-right: 10px;">
<input type="radio" value="7e7f6887-c0ce-4dc3-bb95-2b9ef92fc903.jpg" id="mainPicture1" name="mainPicture" >Main picture<br>
</a>
</td>
<td class="col_actions">
<a href="#" style="color:#808080; text-align: center;" >
<i class="fa fa-times" aria-hidden="true" ></i>
</a>
</td>
</tr>
<tr >
<td class="col_name" >
<div class="box small">
<img src="pics/5/7e92cc5c-73e7-451b-9ee8-2ae43c1b0125.jpg"/>
</div>
</td>
<td class="col_actions">
<a style="color:#808080; margin-right: 10px;">
<input type="radio" value="7e92cc5c-73e7-451b-9ee8-2ae43c1b0125.jpg" id="mainPicture2" name="mainPicture" >Main picture<br>
</a>
</td>
...
on the controller:
@PostMapping("/update/{id}")
public String updateUser(@PathVariable("id") long id, @Valid UserPayload userPayload,
BindingResult result, Model model) {
System.out.println("===================");
System.out.println( userPayload.getMainPicture());
System.out.println("===================");
..
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(NON_NULL)
public class UserPayload implements Serializable {
private Long id;
// pics
private System mainPicture;
...
}
but is null and in the template I checked id="mainPicture2"
Solution
You have wrong type in your UserPayload
class. Instead of:
private System mainPicture;
...you should have:
private String mainPicture;
When you change the type then a value binds properly and System.out.println( userPayload.getMainPicture());
will print 7e92cc5c-73e7-451b-9ee8-2ae43c1b0125.jpg
intead of null
.
Edit:
I'll expand my answer a bit.
I've assumed System was mistaken used in place of String.
Otherwise e.g. System
is a class of yours - then your problem is narrowed down to deserialization issue. There is plain text value passed from the form to the controller (i.a. "7e92cc5c-73e7-451b-9ee8-2ae43c1b0125.jpg"
). Java should know the way how to bind such a text to your mainPicture
variable. If mainPicture
is of any custom type of yours then it isn't a simple assignment anymore. Probably a contructor accepting single String
argument would be enough.
Answered By - Jakub Ch.