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.

5 Answers5

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
  • 754
  • 4
  • 11
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
  • 15,141
  • 6
  • 37
  • 57
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,249
  • 9
  • 15
0

We can set the required property of @PathVariable to false to make it optional.

But we will also need to listen for requests that are coming without path variable.

@GetMapping(value = { "/{locale}", "/" }, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> getLocale(@PathVariable("locale") String locale) {
    return new ResponseEntity<>(locale, HttpStatus.OK);
}
Denis Bahlei
  • 33
  • 1
  • 6
-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,520
  • 1
  • 26
  • 33