我有 Controller :
@RestController
public class AdminController {
@PutMapping("/path/max_file_size")
public void setMaxFileSize(@ModelAttribute MaxFileSizeDto size) {
System.out.println(size.getSize());
}
public static class MaxFileSizeDto {
private long size;
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
}
}
但我总是得到 0
size.getSize()
我做错了什么?
最佳答案
在添加模型之前,您应该记住,Model
和 Controller
应该分开。这意味着将您的模型保留在另一个包或类中。对于发布/放置数据,您应该使用 Object
(String, Integer,Long) 而不是 primitive
(int, long etc) .
假设你的模型类
MaxFileSizeDto.java
public static class MaxFileSizeDto {
private Long size;
public Long getSize() {
return size;
}
public void setSize(Long size) {
this.size = size;
}
}
你的 Controller 类将是:
@RestController
public class AdminController {
@PutMapping("/path/max_file_size")
public void setMaxFileSize(@ModelAttribute MaxFileSizeDto size) {
System.out.println(size.getSize());
}
}
当您将数据作为 application/x-www-form-urlencoded
发送时,您的数据将以这种格式发送并直接绑定(bind)到 @ModelAttribute
定义的类中。
param1=data1¶m2=data2¶m3=data3
但是 postman 在内部以这种格式发送数据。
如果您想将数据作为 @RequestBody
发送,那么您应该使用 json 数据,说明您的内容类型是 application/json
。为此,您应该从 postman 中选择 raw
单选按钮,然后从下拉列表中选择 application/json
。(行中的最后一个元素)
在这些情况下,数据将是
{
"size":123456
}
关于java - 如何将 long 传递给 spring PUT Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47527811/