我正在尝试以不涉及任何页面刷新的方式重写我的表单。换句话说,我不希望浏览器在提交时发出任何 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]'
我也解决了这个问题
Collection
,而不是一个数组),所以new StringJoiner(", ", "{", "}")
→new StringJoiner(", ", "[", "]")
p>用户名:$('input[name=username]').val()
→用户名:$(this).find('input[name=username]')。 val()
或更好用户名:$(this).find('[name=username]').val()
等等department
由元素表示,因此
'input[name=department]'
→'select[name=department]'
或'[name=department]'