Spring Boot 如何正确地将Collection从表单传递到JS事件处理程序,然后传递到REST控制器?

h7wcgrx3  于 2023-04-11  发布在  Spring
关注(0)|答案(1)|浏览(105)

我正在尝试以一种不涉及任何页面刷新的方式重写表单。换句话说,我不希望浏览器在提交时发出任何GET/POST请求。jQuery应该可以帮助我。这是我的表单(我有几个):

<!-- I guess this action doesn't make much sense anymore -->
    <form action="/save-user" th:object="${user}" method="post">
         <input type="hidden" name="id" th:value="${user.id}">
    
         <input type="hidden" name="username"
              th:value="${user.username}">
    
         <input type="hidden" name="password"
              th:value="${user.password}">
    
         <input type="hidden" name="name" th:value="${user.name}">
    
         <input type="hidden" name="lastName"
              th:value="${user.lastName}">
    
         <div class="form-group">
              <label for="departments">Department: </label>
              <select id="departments" class="form-control"
                       name="department">
                  <option th:selected="${user.department == 'accounting'}"
                          th:value="accounting">Accounting
                  </option>
                  <option th:selected="${user.department == 'sales'}"
                          th:value="sales">Sales
                  </option>
                  <option th:selected="${user.department == 'information technology'}"
                          th:value="'information technology'">IT
                  </option>
                  <option th:selected="${user.department == 'human resources'}"
                          th:value="'human resources'">HR
                  </option>
                  <option th:selected="${user.department == 'board of directors'}"
                          th:value="'board of directors'">Board
                  </option>
              </select>
          </div>
    
          <div class="form-group">
              <label for="salary">Salary: </label>
              <input id="salary" class="form-control" name="salary"
                     th:value="${user.salary}"
                     min="100000" aria-describedby="au-salary-help-block"
                     required/>
              <small id="au-salary-help-block"
                     class="form-text text-muted">100,000+
              </small>
          </div>
    
          <input type="hidden" name="age" th:value="${user.age}">
    
          <input type="hidden" name="email" th:value="${user.email}">
    
          <input type="hidden" name="enabledByte"
                 th:value="${user.enabledByte}">
          
          <!-- I guess I should JSON it somehow instead of turning into regular strings -->
          <input type="hidden" th:name="authorities"
                 th:value="${#strings.toString(user.authorities)}"/>
    
          <input class="btn btn-primary d-flex ml-auto" type="submit"
                 value="Submit">
      </form>

以下是我的JS:

$(document).ready(function () {
    $('form').on('submit', async function (event) {
        event.preventDefault();

        let user = {
            id: $('input[name=id]').val(),
            username: $('input[name=username]').val(),
            password: $('input[name=password]').val(),
            name: $('input[name=name]').val(),
            lastName: $('input[name=lastName]').val(),
            department: $('input[name=department]').val(),
            salary: $('input[name=salary]').val(),
            age: $('input[name=age]').val(),
            email: $('input[name=email]').val(),
            enabledByte: $('input[name=enabledByte]').val(),
            authorities: $('input[name=authorities]').val()

            /*
            ↑ i tried replacing it with authorities: JSON.stringify($('input[name=authorities]').val()), same result
            */
        };

        await fetch(`/users`, {
            method: 'PUT',
            headers: {
                ...getCsrfHeaders(),
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(user) // tried body : user too
        });

    });
});

function getCsrfHeaders() {
    let csrfToken = $('meta[name="_csrf"]').attr('content');
    let csrfHeaderName = $('meta[name="_csrf_header"]').attr('content');

    let headers = {};
    headers[csrfHeaderName] = csrfToken;
    return headers;
}

下面是我的REST控制器处理程序:

// maybe I'll make it void. i'm not sure i actually want it to return anything
    @PutMapping("/users")
    public User updateEmployee(@RequestBody User user) {
        service.save(user); // it's JPARepository's regular save()
        return user;
    }

User实体:

@Entity
@Table(name = "users")
@Data
@EqualsAndHashCode
public class User implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column
    private long id;
    @Column(nullable = false, unique = true)
    private String username;
    @Column(nullable = false)
    private String password;
    @Column
    private String name;
    @Column(name = "last_name")
    private String lastName;
    @Column
    private String department;
    @Column
    private int salary;
    @Column
    private byte age;
    @Column
    private String email;
    @Column(name = "enabled")
    private byte enabledByte;
    @ManyToMany
    @JoinTable(name = "user_role",
            joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id"),
                    @JoinColumn(name = "username", referencedColumnName = "username")},
            inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "id"),
                    @JoinColumn(name = "role", referencedColumnName = "role")})
    @EqualsAndHashCode.Exclude
    private Set<Role> authorities;

Role实体:

@Entity
@Table(name = "roles")
@Data
@EqualsAndHashCode
public class Role implements GrantedAuthority {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column
    private long id;
    @Column(name = "role", nullable = false, unique = true)
    private String authority;
    @ManyToMany(mappedBy = "authorities")
    @EqualsAndHashCode.Exclude
    private Set<User> userList;

当我按下提交按钮时,我的控制台里会出现这个

WARN 18252 --- [io-8080-exec-10] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.HashSet<pp.spring_bootstrap.models.Role>` from String value (token `JsonToken.VALUE_STRING`)]

似乎我应该以某种方式传递Collection的JSON表示,而不仅仅是String

@Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(new Formatter<Set<Role>>() {
            @Override
            public Set<Role> parse(String text, Locale locale) {
                Set<Role> roleSet = new HashSet<>();
                String[] roles = text.split("^\\[|]$|(?<=]),\\s?");
                for (String roleString : roles) {
                    if (roleString.length() == 0) continue;
                    String authority =
                            roleString.substring(roleString.lastIndexOf("=") + 2,
                                    roleString.indexOf("]") - 1);
                    roleSet.add(service.getRoleByName(authority));
                }
                return roleSet;
            }

            @Override
            public String print(Set<Role> object, Locale locale) {
                return null;
            }
        });
    }

我谷歌了一下,发现Thymeleaf没有任何toJson()方法。我的意思是我可以自己写方法,但我不知道如何在Thymeleaf模板中使用它们。此外,it may not be the most optimal solution
这是一个 Boot 项目,所以我有Jackson数据绑定库

如何将Collection从表单正确传递到JS事件处理程序,然后传递到REST控制器?

我检查了StackOverflow提出的多个类似问题,它们看起来并不相关(例如,它们涉及不同的编程语言,如C#或PHP)

**UPD:**我刚才试过了,可惜也不行!(错误信息相同)

// inside my config
    @Bean
    public Function<Set<Role>, String> jsonify() {
        return s -> {
            StringJoiner sj = new StringJoiner(", ", "{", "}");
            for (Role role : s) {
                sj.add(String.format("{ \"id\" : %d, \"authority\" : \"%s\" }", role.getId(), role.getAuthority()));
            }
            return sj.toString();
        };
    }
<input type="hidden" th:name="authorities" 
           th:value="${@jsonify.apply(user.authorities)}"/>

不过,该方法可以按预期工作

$(document).ready(function () {
    $('form').on('submit', async function (event) {
        /*
        ↓ logs:
          authorities input: {{ "id" : 1, "authority" : "USER" }}
        */
        console.log('authorities input: ' + 
                   $('input[name=authorities]').val());

**UPD 2:**GPT 4建议

authorities: JSON.parse($('input[name=authorities]').val())

现在真的很奇怪。数据库仍然没有改变,但是!IDE控制台现在没有错误,也没有提到PUT请求(以前的尝试中有)!此外,浏览器日志有以下消息

Uncaught (in promise) SyntaxError: Expected property name or '}' in JSON at position 1
    at JSON.parse (<anonymous>)
    at HTMLFormElement.<anonymous> (script.js:28:31)
    at HTMLFormElement.dispatch (jquery.slim.min.js:2:43114)
    at v.handle (jquery.slim.min.js:2:41098)

我不知道这是什么意思!

**UPD 3:**GPT 4很聪明。无论如何,比我聪明。这是绝对正确的。它在UPD 2中不起作用的原因是我忽略了它说的另一件事:

authorities字段应该作为对象的数组而不是字符串发送。
这意味着我应该使用方括号,而不是花括号,作为我的StringJoiner前缀和后缀:

// I also added some line breaks, but I doubt it was necessary
    @Bean
    public Function<Set<Role>, String> jsonify() {
        return s -> {
            StringJoiner sj = new StringJoiner(",\n", "[\n", "\n]");
            for (Role role : s) {
                sj.add(String.format("{\n\"id\" : %d,\n\"authority\" : \"%s\"\n}", role.getId(), role.getAuthority()));
            }
            return sj.toString();
        };
    }

我也改了,比如说这个

username: $('input[name=username]').val()

我真傻,没有马上做。

username: $(this).find('input[name=username]').val()

和-中提琴-它现在工作!
GPT 4也注意到我用了

'input[name=department]'

而不是

'select[name=department]'

我也修好了

vom3gejh

vom3gejh1#

1.它应该是一个对象数组(即使它是一个Collection,而不是一个数组),所以
new StringJoiner(", ", "{", "}")new StringJoiner(", ", "[", "]")
1.它应该以窗体的子级为目标
username: $('input[name=username]').val()username: $(this).find('input[name=username]').val(),依此类推

  1. department<select>元素so表示
    'input[name=department]''select[name=department]'

相关问题