英文:
Set default value in RequestBody if variable is empty or null
问题
我有一个示例控制器方法
public void generateFile(@RequestBody final FileRequest request) {
...
}
有时候并不是所有 FileRequest 类的字段都被填充,是否有办法在请求的值为空或为null时设置默认值?
我的意思是像 @Default 这样的东西。
英文:
I have example controller method
public void generateFile(@RequestBody final FileRequest request) {
...
}
Sometimes not all fields of this class FileRequest are filled, is there any way to set the default value when the value in the request is empty or null?
I mean something like @Default
答案1
得分: 3
// class User
import lombok.Data;
@Data
public class User {
private String name;
private String address = "beijing";
private int age = 10;
}
// in Class restConctroller
@RequestMapping(value = "/res1/data")
public Object postData(@RequestBody User user) {
return user;
}
After posting to http://localhost:8080/res1/data with name='aaa', you will receive the following result:
{
"name": "aaa",
"address": "beijing",
"age": 10
}
英文:
In FileRequest class, setting field with a value. If field not filled, it will use default value in class. Use lombok, class is too simple. like as below:
// class User
import lombok.Data;
@Data
public class User {
private String name;
private String address="beijing";
private int age=10;
}
// in Class restConctroller
@RequestMapping(value = "/res1/data")
public Object postData(@RequestBody User user){
return user;
}
after post http://localhost:8080/res1/data with name='aaa', you will get result as
{
"name": "aaa",
"address": "beijing",
"age": 10
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论