Is it possible to have empty RequestParam values use the defaultValue?

后端 未结 5 1841
北海茫月
北海茫月 2020-11-30 20:15

if I have a a request mapping similar to the following:

@RequestMapping(value = \"/test\", method = RequestMethod.POST)
@ResponseBody
public void test(@Reque         


        
相关标签:
5条回答
  • 2020-11-30 21:03

    You can also do something like this -

     @RequestParam(value= "i", defaultValue = "20") Optional<Integer> i
    
    0 讨论(0)
  • 2020-11-30 21:08

    You could change the @RequestParam type to an Integer and make it not required. This would allow your request to succeed, but it would then be null. You could explicitly set it to your default value in the controller method:

    @RequestMapping(value = "/test", method = RequestMethod.POST)
    @ResponseBody
    public void test(@RequestParam(value = "i", required=false) Integer i) {
        if(i == null) {
            i = 10;
        }
        // ...
    }
    

    I have removed the defaultValue from the example above, but you may want to include it if you expect to receive requests where it isn't set at all:

    http://example.com/test
    
    0 讨论(0)
  • 2020-11-30 21:08

    You can keep primitive type by setting default value, in the your case just add "required = false" property:

    @RequestParam(value = "i", required = false, defaultValue = "10") int i
    

    P.S. This page from Spring documentation might be useful: Annotation Type RequestParam

    0 讨论(0)
  • 2020-11-30 21:13

    This was considered a bug in 2013: https://jira.spring.io/browse/SPR-10180

    and was fixed with version 3.2.2. Problem shouldn't occur in any versions after that and your code should work just fine.

    0 讨论(0)
  • 2020-11-30 21:15

    You can set RequestParam, using generic class Integer instead of int, it will resolve your issue.

       @RequestParam(value= "i", defaultValue = "20") Integer i
    
    0 讨论(0)
提交回复
热议问题