【问题标题】:How to serialize form data with collection field and deserialize it on the server side?如何用集合字段序列化表单数据并在服务器端反序列化?
【发布时间】:2021-10-19 18:00:20
【问题描述】:

我有一个简单的 HTML 表单,它表示后端用户对象的数据。在服务器上,有一个带有休息控制器的 Spring Boot 应用程序。 这是表格:

<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>

所以,我需要从表单中取出用户数据,通过feth API发送到服务器,然后放到数据库中。

  1. 第一个问题是:如何将表单数据(使用js)序列化为JSON,意味着它具有Set(roles)表示的值? 我想,通过 fetch 发送的 JSON 对象应该是这样的:
{ “名字”: “鲍勃”,
“姓氏”:“马利”,
    “年龄”:30,
    “电子邮件”:“bob@mail.com”,
    “密码”:“密码”,
    “角色”:[“管理员”,“用户”]//或只是[“用户”]或[“管理员”]
}

如何从表单中获取数据并获取这样的 JSON?

  1. 将请求正文中的传入用户 JSON 数据转换为休息控制器中的用户 java 对象的最佳方法是什么?我通过 Gson 和 Object mapper 尝试过,但没有成功。到目前为止,我通过 JSON 字符串进行迭代并从 JSON 键和值构建新用户,但这种方法似乎太复杂了。这是我尝试解决此问题的第四天,我需要帮助!

【问题讨论】:

    标签: javascript java html rest fetch


    【解决方案1】:

    这里有几点需要考虑:

    1- 在提交之前,从 JS 文件中的表单内容创建 JSON:

    例子:

    function onSubmit( form ){
      var data = JSON.stringify( $(form).serializeArray() );
    
      console.log( data );
      return false; //don't submit
    }
    

    参考:Serialize form data to JSON

    2- 使用 Fetch API (Post) 将创建的 JSON 发送到您的后端 springboot 应用程序

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

    3- 您的后端 Springboot 应用程序需要有一个带有一个端点的控制器来接受此调用。

    您的用户 pojo 也需要在后端应用程序中定义。

    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 会自行反序列化您发送到 User pojo 类的 JSON 字符串。你根本不需要做任何事情。

    您确实需要以下依赖项:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多