How to handle a @RequestParam not defined

83 views Asked by At

So, as the title says i have this piece of code here

@GetMapping("/concat")
public String conc(@RequestParam("c1") String con1,@RequestParam("c2") String con2){
    return stringService.conc(con1, con2);
}

which just return a string concatenated with another string. my problem here is, i want to NOT define the "c2" param and either says it's null or say nothing at all as it NEEDS to work with even just one param.

how do i achieve that?

i tried this

@GetMapping("/concat")
public String conc(@RequestParam("c1") String con1,@RequestParam("c2") String con2){
    if(con2 == null){
        return con1;
    }else{
        return stringService.conc(con1, con2);
    }
}

it obviously didn't work and i don't know how to use @ExceptionHandler (if that is the solution)

3

There are 3 answers

1
dan1st might be happy again On BEST ANSWER

You can specify a default value in @RequestParam: @RequestParam(name = "yourParameterName", defaultValue = "yourParameterDefaultValue")

Here, I just use an empty String as the default value:

@GetMapping("/concat")
public String conc(@RequestParam("c1") String con1,@RequestParam(name="c2",defaultValue = "") String con2){
    return stringService.conc(con1, con2);
}

This will concatenate it with the empty string. Requesting /concat?c1=a will call conc("a","").

Alternatively, you can use required=false and do an explicit null check:

@GetMapping("/concat")
public String conc(@RequestParam("c1") String con1,@RequestParam(name = "c2", required = false) String con2){
    if(con2 == null){
        return con1;
    }else{
        return stringService.conc(con1, con2);
    }
}

Requesting /concat?c1=a will call conc("a",null).

0
Unmitigated On

Set required = false in the annotation to make it optional.

public String conc(@RequestParam("c1") String con1, 
                   @RequestParam(name = "c2", required = false) String con2){
    return stringService.conc(con1, con2 != null ? con2 : "");
}
0
Toni On

One option is to use required = false as suggested, but you can also take advantage of Optional as follows:

@GetMapping("/concat")
public String conc(@RequestParam("c1") String con1, @RequestParam("c2") Optional<String> con2){
    return con2.map(i->stringService.conc(con1, i)).orElse(con1);
}