如何正確地將 Collection 從我的表單傳遞到 JS 事件處理程序,然後傳遞到 REST 控制器?
P粉807397973
P粉807397973 2024-01-10 17:25:43
0
1
415

我正在嘗試以不涉及任何頁面刷新的方式重寫我的表單。換句話說,我不希望瀏覽器在提交時發出任何 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;

角色實體:

@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。在我之前的專案中,沒有使用 jQuery,String 已使用我的自訂 Formatter 成功反序列化

@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 模板中使用它們。此外,這可能不是最優的解決方案

這是一個 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());

UPD2:GPT4 建議這樣做

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)

不知道什麼意思!

UPD3:GPT4 很聰明。反正比我聰明。這是絕對正確的。它在 UPD2 中不起作用的原因是我忽略了它所說的另一件事:

權限欄位應作為物件的陣列而不是字串發送。

這意味著我應該使用方括號,而不是大括號,作為我的 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()

並且 - 中提琴 - 現在可以使用了!

GPT4 也注意到我使用了

'input[name=department]'

而不是

'select[name=department]'

我也解決了這個問題

P粉807397973
P粉807397973

全部回覆(1)
P粉138871485
  1. 它應該是一個物件陣列(即使它是一個 Collection,而不是一個陣列),所以

new StringJoiner(", ", "{", "}")new StringJoiner(", ", "[", "]")# p>

  1. 它應該以表單的子級為目標

使用者名稱:$('input[name=username]').val()使用者名稱:$(this).find('input[name=username]') 。 val() 或更好使用者名稱:$(this).find('[name=username]').val() 等等

  1. department 元素表示,因此

'input[name=department]''select[name=department]''[name=department]'#

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板