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.

1

5 Answers 5

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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>

Comments

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);
}

Comments

-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);
}

2 Comments

there is no defaultValue in @PathVariable
there is nothing like defaultValue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.