0
@GetMapping(value = "/{locale}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getLocale(@PathVariable("locale") String locale) {
    return new ResponseEntity<>(locale, HttpStatus.OK);
}

I want if locale is null, I can set a default value "english" in it.

4 Answers4

2

By default PathVariable is required but you can set it optional as :

@GetMapping(value = "/{locale}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getLocale(@PathVariable(name="locale", required= 
false) String locale) {
//set english as default value if local is null   
locale = locale == null? "english": locale;
return new ResponseEntity<>(locale, HttpStatus.OK);
}
JAR
  • 649
  • 2
  • 10
0

You can use required false attribute and then can check for null or empty string value. Refer this thread

getLocale(@PathVariable(name ="locale", required= false) String locale

And then check for null or empty string.

Alien
  • 13,439
  • 5
  • 35
  • 53
0

You cannot provide default value to spring path variable as of now.

You can do the following obvious thing:

@GetMapping(value = "/{locale}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getLocale(@PathVariable("locale") String locale) {
    locale = locale == null? "english": locale;
    return new ResponseEntity<>(locale, HttpStatus.OK);
}

But more appropriate is to use Spring i18n.CookieLocaleResolver, so that you do not need that path variable anymore:

    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
        <property name="defaultLocale" value="en"/>
    </bean>
eugen
  • 1,149
  • 8
  • 13
-1

You just need to provide default value

@GetMapping(value = "/{locale}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getLocale(@PathVariable("locale", defaultValue="english") String locale) {
    return new ResponseEntity<>(locale, HttpStatus.OK);
}
Swarit Agarwal
  • 2,276
  • 22
  • 31