【问题标题】:Modifying the request parameters in HTTP GET request while passing it to controller修改 HTTP GET 请求中的请求参数,同时将其传递给控制器
【发布时间】:2020-08-26 17:43:21
【问题描述】:

我需要修改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);
}

【问题讨论】:

标签: java spring-boot model-view-controller get http-request-parameters


【解决方案1】:

您可以添加自定义Formatter or Converter,例如:

  1. 实现自定义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();
        }
    }
  1. 注册自定义Formatter:
    @Configuration
    @EnableWebMvc
    public class WebConfig implements WebMvcConfigurer {

        @Override
        public void addFormatters(FormatterRegistry registry) {
            registry.addFormatter(new MyDoubleFormatter());
        }
    }

【讨论】:

    猜你喜欢
    • 2018-10-07
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    相关资源
    最近更新 更多