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

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

Set default value in RequestBody if variable is empty or null

问题

我有一个示例控制器方法

  1. public void generateFile(@RequestBody final FileRequest request) {
  2. ...
  3. }

有时候并不是所有 FileRequest 类的字段都被填充,是否有办法在请求的值为空或为null时设置默认值?

我的意思是像 @Default 这样的东西。

英文:

I have example controller method

  1. public void generateFile(@RequestBody final FileRequest request) {
  2. ...
  3. }

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

  1. // class User
  2. import lombok.Data;
  3. @Data
  4. public class User {
  5. private String name;
  6. private String address = "beijing";
  7. private int age = 10;
  8. }
  9. // in Class restConctroller
  10. @RequestMapping(value = "/res1/data")
  11. public Object postData(@RequestBody User user) {
  12. return user;
  13. }

After posting to http://localhost:8080/res1/data with name='aaa', you will receive the following result:

  1. {
  2. "name": "aaa",
  3. "address": "beijing",
  4. "age": 10
  5. }
英文:

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:

  1. // class User
  2. import lombok.Data;
  3. @Data
  4. public class User {
  5. private String name;
  6. private String address="beijing";
  7. private int age=10;
  8. }
  9. // in Class restConctroller
  10. @RequestMapping(value = "/res1/data")
  11. public Object postData(@RequestBody User user){
  12. return user;
  13. }

after post http://localhost:8080/res1/data with name='aaa', you will get result as

  1. {
  2. "name": "aaa",
  3. "address": "beijing",
  4. "age": 10
  5. }

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:

确定