java - 如何在 Spring 传递 @PathVariable ("timeZoneId")?

标签 java spring spring-boot spring-data path-variables

我有以下@RestController Spring Boot 1.5.9 中的方法:

@GetMapping(value = "/today/{timeZoneId}", produces = MediaType.APPLICATION_JSON_VALUE)
public Instant getToday(@PathVariable("timeZoneId") String timeZoneId) {
  return getNextPublishingDateTime(Instant.now(), timeZoneId);
}

当我 GET/today/Europe/Paris ,我有一个404错误。

我尝试GET/today/Europe%2FParis但还得到了404 .

这是由于 timeZoneId 中的斜线造成的.

如何使用@PathVariable对于我的timeZoneId在 Spring ?

最佳答案

一种可能的方式如下,

@GetMapping(value = "/today/{timeZoneIdPrefix}/{timeZoneIdSuffix}", produces = MediaType.APPLICATION_JSON_VALUE)
public Instant getToday(@PathVariable("timeZoneIdPrefix") String timeZoneIdPrefix,@PathVariable("timeZoneIdSuffix") String timeZoneIdSuffix) {
  String timeZoneId = timeZoneIdPrefix +"/"+ timeZoneIdSuffix;
  return getNextPublishingDateTime(Instant.now(), timeZoneId);
}

还有一种方法是,不要像 Europe/Paris 那样传递,而是像 Europe-Paris 那样传递,然后将 - 替换为 /

 return getNextPublishingDateTime(Instant.now(), timeZoneId.replace("-","/"));

关于java - 如何在 Spring 传递 @PathVariable ("timeZoneId")?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61360014/

相关文章:

java - 对数组元素的奇数索引求和

java - SharedPreferences 未在 onResume() 中更新

java - 使用 JOOQ 插入忽略多个 pojo

java - Tomcat 或 Jetty 上的 Spring Web 应用程序 Controller 内基于事件的编程

java - 构造函数抛出异常后可以调用finalize吗?

java - 'class "org.bouncycaSTLe.asn1.ASN1Primitive"'s signer information does not match signer information of other classes in the same package' 使用 Itext

java - 实例变量的 Spring 作用域用法

java - 具有基于 java 的配置的 Spring Batch 的可跳过异常类

Spring Boot 所需的请求部分 'file' 不存在

java - 在 Spring Boot 中设置自己的安全性