简体   繁体   中英

How to serialize form data with collection field and deserialize it on the server side?

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.

  1. 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?

  1. 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!

There are a few things to consider here:

1- Creating a JSON from your form content inside your JS file, before submission:

Example:

function onSubmit( form ){
  var data = JSON.stringify( $(form).serializeArray() );

  console.log( data );
  return false; //don't submit
}

Ref: Serialize form data to JSON

2- Send Created JSON using Fetch API (Post) towards your backend springboot application

  const response = await fetch("backend:8080/api/user", {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: data  // <-- Must be in JSON format
  });

3- Your backend Springboot application needs to have a Controller with a an endpoint that accepts this call.

Your User pojo needs to be defined in the backend application as well.

public class User{

    @JsonProperty("firstName")
    private String firstName;

    @JsonProperty("lastName")
    private String lastName;

}



@RestController
@RequestMapping(value = "/api")
public class EmailControllerImpl {

    @PostMapping("/user")
    public ResponseEntity<String> addUser(@RequestBody User userPojo){

          //Deal with your User

    }

Springboot will de serialize the JSON string you sent into the User pojo class on its own. You dont have to do anything at all.

You do need the following dependency:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM