java - 修改 HTTP GET 请求中的请求参数,同时将其传递给控制器
问题描述
我需要修改GET URL“http://localhost:8081/qeats/v1/restaurants?latitude=87.97864&longitude=20.82345”中的请求参数,同时将其发送到spring boot控制器,以便纬度和经度值只是精确的直到小数点后一位。例如“http://localhost:8081/qeats/v1/restaurants?latitude=87.9&longitude=20.8”
@GetMapping(RESTAURANTS_API)
public ResponseEntity<GetRestaurantsResponse> getRestaurants(
@RequestParam Double latitude,
@RequestParam Double longitude, GetRestaurantsRequest getRestaurantsRequest) {
log.info("getRestaurants called with {}", getRestaurantsRequest);
GetRestaurantsResponse getRestaurantsResponse;
if (getRestaurantsRequest.getLatitude() != null && getRestaurantsRequest.getLongitude() != null
&& getRestaurantsRequest.getLatitude() >= -90
&& getRestaurantsRequest.getLatitude() <= 90
&& getRestaurantsRequest.getLongitude() >= -180
&& getRestaurantsRequest.getLongitude() <= 180) {
getRestaurantsResponse = restaurantService.findAllRestaurantsCloseBy(
getRestaurantsRequest, LocalTime.now());
log.info("getRestaurants returned {}", getRestaurantsResponse);
return ResponseEntity.ok().body(getRestaurantsResponse);
} else {
return ResponseEntity.badRequest().body(null);
}
解决方案
您可以添加自定义Formatter 或 Converter,例如:
- 实现自定义
Formatter
:
public class MyDoubleFormatter implements Formatter<Double> {
private final DecimalFormat decimalFormat = new DecimalFormat("#.#");
@Override
public Double parse(String text, Locale locale) {
return Double.parseDouble(decimalFormat.format(Double.parseDouble(text)));
}
@Override
public String print(Double value, Locale locale) {
return value.toString();
}
}
- 注册自定义
Formatter
:
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatter(new MyDoubleFormatter());
}
}
推荐阅读
- sql - Finding the number of agents working for a manager in a certain week
- c++ - 在 C++ 中包装浮点数计数器
- c - 使用具有固定宽度整数类型变量的 printf 宽度说明符
- tensorflow - 使用 MobileNetV1 的多位数分类器
- javascript - ReactNative:无法从 NativeModules 调用函数
- node.js - MEAN Stack:当 Angular 在 Node 文件夹中时,如何从 Node 启动 Angular
- javascript - 如何更改画布文本的字体大小
- rest-assured-jsonpath - RestAssured - JsonPath 表达式过滤器不起作用
- python - 如何按主题列出多个主题的订阅?
- c# - 使用 c# 从 Sqlite 表中获取特定客户的值的总和