如何解决在将HTTP GET请求传递给控制器时修改请求参数
我需要在将其发送到Spring Boot控制器时修改GET URL中的请求参数“ http:// localhost:8081 / qeats / v1 / restaurants?latitude = 87.97864&longitude = 20.82345”,以使纬度和经度值仅精确到小数点后一位。例如“ 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 or 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());
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。