在变量为空或为null时,在RequestBody中设置默认值。

huangapple go评论71阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2020年10月14日 15:42:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/64348731.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定