javaspringget-mapping

How to handle a @RequestParam not defined


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)


Solution

  • 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).