Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@RequestParam defaultvalue does not accept enum value as a default value

I am using spring rest controller.

Here is the code.

@RequestParam(value = "status", required = false, defaultValue = StatusEnum.STATUS.toString()) 

If i use enum as a defaultValue i am getting The value for annotation attribute RequestParam.defaultValue must be a constant expression.

As per my understanding it should accept enum as a default value.

Please advice.

like image 490
Chetan Shirke Avatar asked Jul 19 '12 05:07

Chetan Shirke


People also ask

Do @RequestParam has default value?

The default value of the @RequestParam is used to provide a default value when the request param is not provided or is empty. In this code, if the person request param is empty in a request, the getName() handler method will receive the default value John as its parameter.

How do you pass enum in Request param?

Use Enums as Request Parameters Or we can use it as a PathVariable: @GetMapping("/findbymode/{mode}") public String findByEnum(@PathVariable("mode") Modes mode) { // ... } When we make a web request, such as /mode2str? mode=ALPHA, the request parameter is a String object.

How do I set default value in RequestParam?

By default, @RequestParam requires query parameters to be present in the URI. However, you can make it optional by setting @RequestParam 's required attribute to false . In the above example, the since query param is optional: @RequestParam(value="since", required=false) ).

Is @RequestParam optional?

Optional Request ParametersMethod parameters annotated with @RequestParam are required by default.


1 Answers

Since it has to be a String, and it has to be a constant expression, your only real option here is to use the value that will work for Enum.valueOf(), since that's how this is eventually resolved.

Specifically, yours should read

@RequestParam(value = "status", required = false, defaultValue = "STATUS") 

Assuming, of course, that "STATUS" is the string value for StatusEnum.STATUS.

like image 67
biggusjimmus Avatar answered Oct 16 '22 13:10

biggusjimmus