如何为路径变量设置默认值?

时间:2020-03-15 06:58:41

标签: spring spring-boot spring-mvc

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

我想如果语言环境为null,则可以在其中设置默认值“英语”。

4 个答案:

答案 0 :(得分:2)

默认情况下,PathVariable是必需的,但您可以将其设置为可选:

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

答案 1 :(得分:0)

您可以使用必需的false属性,然后可以检查null或空字符串值。请参阅this thread

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

然后检查是否为空或空字符串。

答案 2 :(得分:0)

到目前为止,您无法为弹簧路径变量提供默认值。

您可以做以下显而易见的事情:

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

但是更合适的是使用Spring i18n.CookieLocaleResolver,这样您就不再需要该路径变量了:

    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
        <property name="defaultLocale" value="en"/>
    </bean>

答案 3 :(得分:-1)

您只需要提供默认值

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