使用拦截器或过滤器对我来说听起来太过分了。当您只想将某些日期时间字段转换为用户特定的时区时,检查每个可以转换为用户时区的日期时间字段的请求太多了。
更简单的方法是在向/从客户端反序列化您的 java 对象时指定自定义 JsonSerializer 和 JsonDeserializer。由于您使用的是 Java 8,因此您可以使用 ZonedDateTime 将 DateTime 和 Zone 一起存储在一个字段中。
在会话中存储 userTimeZone 是一种常见的做法。自定义序列化程序需要是 spring bean,以便您可以注入会话,然后获取保存在其中的 userTimeZone。
分享一些伪代码
DTO:
public class TheDTO {
@JsonSerialize(using = UserTimeZoneAwareSerializer.class)
@JsonDeserialize(using = UserTimeZoneAwareDeserializer.class)
private ZonedDateTime dateTime;
public ZonedDateTime getDateTime() {
return dateTime;
}
public void setDateTime(ZonedDateTime dateTime) {
this.dateTime = dateTime;
}
}
序列化程序,从您的处理程序到客户端:
@Component
public class UserTimeZoneAwareSerializer extends JsonSerializer<ZonedDateTime> {
@Autowired
private HttpSession httpSession;
@Override
public void serialize(ZonedDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
// Grab the userTimeZone from the session then convert from UTC to userTimeZone
gen.writeObject(/**/);
}
}
反序列化器,从客户端到您的处理程序:
@Component
public class UserTimeZoneAwareDeserializer extends JsonDeserializer<ZonedDateTime> {
@Autowired
private HttpSession httpSession;
@Override
public ZonedDateTime deserialize(JsonParser p, DeserializationContext ctxt)
// Grab the userTimeZone then convert from userTimeZone to UTC
// ...
}
}
通过这种方式,您可以轻松地注释您想要了解用户时区的ZonedDateTime 字段。