I’ve got a simple HTML form that represents data of the User objects on the backend side. On the server, there’s a Spring boot application with a rest controller. Here is the form:
<form id="new-user-form">
<label class="text-center col-form-label"><b>First Name:</b></label>
<input type="text" id="firstname" name="firstname" value="" />
<label class="text-center col-form-label"><b>Last Name:</b> </label>
<input type="text" id="lastname" name="lastname" value="" />
<label class="text-center col-form-label"><b>Age:</b></label>
<input type="number" id="age" name="age" value="" />
<label class="text-center col-form-label"><b>E-mail:</b></label>
<input type="email" id="email" name="email" value="" />
<label class="text-center col-form-label"><b>Password:</b></label>
<input type="password" id="password" name="password" value="" />
<label class="text-center col-form-label"><b>Role:</b></label>
<select class="col-12 form-control" name="roles" multiple size="2">
<option>ADMIN</option>
<option>USER</option>
</select>
<button
type="submit"
id="submit-new-user"
class="btn btn-primary btn-success"
>
Add new user
</button>
</form>
So, I need to take user data from the form, send it to the server via feth API, and put it to the database.
- The first question is: how to serialize form data (using js) to JSON meaning that it has value represented by Set (roles)? I guess, JSON object to be sent via fetch, should look like this:
{ “firstname”: “Bob”, “lastname”: “Marley”, “age”: 30, “email”: “bob@mail.com”, “password”: “password”, “roles”: [“ADMIN”, “USER”] // or just [“USER”] or [“ADMIN”] }
How can I take data from the form and get such JSON?
- Which is the best way to convert incoming in request body User JSON-data to the User java-object in rest controller? I’ve tried via Gson and Object mapper but didn’t succeed. So far I iterate via JSON string and build new users from JSON keys and values, but this approach seems to be too complicated. This is the fourth day I’m trying to resolve this issue, please, I need help!