我正在编写一个 SPRING Controller 来管理一些实体,但在尝试编辑现有对象时遇到了麻烦。
这是我产生问题的 get/post 映射:
@GetMapping(value = "/category/{id}/edit")
public String editCategoryGET(@PathVariable int id, Model model) {
Category category = repositoriesServices.getCategoryById(id);
log.info("editCategoryGET: " + category);
// set model attribute etc....
}
@PostMapping(value = "/category/{id}/edit")
public @ResponseBody
ResponseEntity editCategoryPOST(@PathVariable int id, Category category) {
log.info("editCategoryPOST: " + category);
// code...
}
类别类是这样的:
@Entity
@Table(name = "categories")
public class Category {
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private int id;
private String name;
@Lob
private String imageBase64;
@Transient
private MultipartFile image;
// getter setter
}
当我尝试编辑Category
对象时,它直接来自数据库,正如您在日志底部看到的那样,但是当它来自POST
时, imageBase64
字段为 null
。
editCategoryGET: Category{id=1, name='vdsvsdv', imageBase64='data:image/png;base6...'}
editCategoryPOST: Category{id=1, name='vdsvsdv', imageBase64='null'}
ajax POST
调用是这样完成的:
var form = $('#form');
$.ajax({
type: "POST",
url: form.attr("action"),
data: new FormData(form[0]),
processData: false,
contentType: false,
dataType: 'json'
}).done(.........
我已经读过this ,但是如果我输入 @RequestBody
我会收到此错误:
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'multipart/form-data;boundary=----WebKitFormBoundaryZJlpA2NOKy6YhELW;charset=UTF-8' not supported
即使我添加了 consumes = MediaType.ALL_VALUE
属性。
我知道我可以通过再次调用数据库来获取旧数据来解决,但我希望有一个最干净的方法
解决方案: 我已经解决了编辑后发送 json 数据的问题:
function getFormDataAsJSON() {
var json = {};
json.name = $('#name-input').val();
json.imageBase64 = $('#logo-preview').attr('src');
return json;
}
var form = $('#form');
var postData = {};
postData.formData = new FormData(form[0]);
var flag = false;
if ($('#div-visible-only-in-edit-way').length !== 0) {
flag = true;
postData.jsonData = getFormDataAsJSON();
}
$.ajax({
type: "POST",
url: form.attr("action"),
data: flag ? JSON.stringify(postData.jsonData) : postData.formData,
processData: false,
contentType: flag ? "application/json; charset=utf-8" : false,
dataType: 'json'
}).done(function (e) {
最佳答案
当您添加 @RequestBody 时,您需要 json 数据,但从客户端发送表单数据。
您应该更改 JavaScript 代码以发送 json 请求。
关于javascript - Spring PostMapping 接收具有空值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51689369/