0

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)

dan1st
  • 12,568
  • 8
  • 34
  • 67
CookieXIV
  • 3
  • 1

3 Answers3

3

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 : "");
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

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

dan1st
  • 12,568
  • 8
  • 34
  • 67
  • easiest and most efficient! that is great! didn't really knew you could have a "required" thing that's so much helpful! – CookieXIV Mar 09 '23 at 09:44
0

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);
}
Toni
  • 3,296
  • 2
  • 13
  • 34