java - Spring MVC 自定义格式化程序在测试中工作但在浏览器中失败
问题描述
我有一个控制器:(根据Spring WebMVC @ModelAttribute 参数样式)
@GetMapping("/time/{date}")
@ResponseStatus(OK)
public LocalDate getDate(
@ModelAttribute("date") LocalDate date
) {
return date;
}
LocalDateFormatterLocalDate
从字符串"now"、"today"和典型的"yyyy-MM-dd"格式的字符串中编码s ,并将日期解码回字符串
public class LocalDateFormatter implements Formatter<LocalDate> {}
我已经通过 Spring Test测试了这个控制器。测试通过。
我设置了一个转换服务并用它模拟了一个 MVC:
var conversion = new DefaultFormattingConversionService();
conversion.addFormatterForFieldType(LocalDate.class, new LocalDateFormatter());
mockMvc = MockMvcBuilders
.standaloneSetup(TimeController.class)
.setConversionService(conversionRegistry)
.build();
测试是参数化的,如下所示:
@ParameterizedTest
@MethodSource("args")
void getDate(String rawDate, boolean shouldConvert) throws Exception {
var getTime = mockMvc.perform(get("/time/" + rawDate));
if (shouldConvert) {
// Date is successfully parsed and some JSON is returned
getTime.andExpect(content().contentType(APPLICATION_JSON_UTF8));
} else {
// Unsupported rawDate
getTime.andExpect(status().is(400));
}
}
以下是参数:
private static Stream<Arguments> args() {
// true if string should be parsed
return Stream.of(
Arguments.of("now", true),
Arguments.of("today", true),
Arguments.of("thisOneShouldNotWork", false),
Arguments.of("2014-11-27", true)
);
}
正如我所说,测试通过。
但是从浏览器启动时,任何请求都会收到400错误。
我如何尝试将转换集成到 Spring MVC 中(这些都不起作用):
覆盖
WebMvcConfigurer
的方法:public class ServletConfig implements WebMvcConfigurer { @Override public void addFormatters(FormatterRegistry registry) { registry.addFormatter(new LocalDateFormatter()); // ALSO TRIED registry.addFormatterForFieldType(LocalDate.class, new LocalDateFormatter()); } }
注册一个
FormattingConversionService
@Bean public FormattingConversionService conversionService() { var service = new FormattingConversionService(); service.addFormatter(new LocalDateFormatter()); return service; }
有人可以告诉我有什么问题吗?
PS我知道这不是处理日期的最佳方式,但由于它在 Spring 参考中说这应该有效,所以我想尝试一下。
解决方案
为spring boot定义这个bean:
@Bean
public Formatter<LocalDate> localDateFormatter() {
return new Formatter<LocalDate>() {
@Override
public LocalDate parse(String text, Locale locale) throws ParseException {
if ("now".equals(text))
return LocalDate.now();
return LocalDate.parse(text, DateTimeFormatter.ISO_DATE);
}
@Override
public String print(LocalDate object, Locale locale) {
return DateTimeFormatter.ISO_DATE.format(object);
}
};
}
如果您使用 Spring MVC 定义如下:
@Configuration
@ComponentScan
@EnableWebMvc
public class ServletConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatter(new Formatter<LocalDate>() {
@Override
public LocalDate parse(String text, Locale locale) throws ParseException {
if ("now".equals(text))
return LocalDate.now();
return LocalDate.parse(text, DateTimeFormatter.ISO_DATE);
}
@Override
public String print(LocalDate object, Locale locale) {
return DateTimeFormatter.ISO_DATE.format(object);
}
});
}
}
不要忘记实现today
函数作为参数。
推荐阅读
- scala - 在 Spark 程序中访问 Oozie 配置
- python - 解析跳过元素
- php - PHP中不同语言的序数指标
- netsuite - NetSuite 公司信息页面(新手问题)
- python - 如何在 Pandas 中检索已删除 / Coulmns Rows 记录
- ubuntu - 使用 NGINX 作为反向代理为同一服务器上的网络服务器提供服务
- ios - Carthage Build 失败,使用 Xcode 11.3 的 Cuckoo 库
- mysql - 查询任意相关表时的 JOIN 与 SELECT IN
- objective-c - iOS 13 - captureOutput 永远不会被调用
- python - PostgreSQL:创建扩展 plpythonu 查询在 Ubuntu 19.10 和 PostgreSQL 10.10 上不起作用