gpt4 book ai didi

java - Spring MVC @PathVariable 被视为 @RequestParam

转载 作者:行者123 更新时间:2023-12-02 02:46:53 25 4
gpt4 key购买 nike

我有一个 spring mvc API(XML 配置),内部有多个服务。但是当我尝试添加 @RequestMapping 的服务时包含路径变量/{theCurrencyCode} ,创建的资源不是我所期望的。

我的期望:

http://localhost:8080/api/v3/parameters/currencies/EUR

什么有效:

http://localhost:8080/api/v3/parameters/currencies/{theCurrencyCode}?theCurrencyCode=EUR

这是我的映射:

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@RequestMapping(value = "v3/", produces = { APPLICATION_JSON_VALUE })
public interface ParametersApi {

@RequestMapping(
value = "/parameters/currencies/{theCurrencyCode}",
produces = { "application/json" },
method = RequestMethod.GET)
ResponseEntity<List<Currency>> GetCurrencies(@PathVariable("theCurrencyCode") String theCurrencyCode);

}

实现:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;

@Controller
public class ParametersApiController implements ParametersApi{

private final CurrenciesService service;

@Autowired
public ParametersApiController(CurrenciesService service) {
this.service = service;
}

@Override
public ResponseEntity<List<Currency>> GetCurrencies(String code) {

final List<Currency> currencies = service.getCurrencies(code);

return new ResponseEntity<>(currencies, HttpStatus.OK);
}
}

Swagger UI 证实了这一点,看到 theCurrencyCode作为“参数类型”query而不是path .

Screenshot from swagger UI

如何让我的 @PathVariable 工作?

最佳答案

您的方法实现中缺少 Pathvariable。因此,要修复,您需要编写如下内容:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;

@Controller
public class ParametersApiController implements ParametersApi{

private final CurrenciesService service;

@Autowired
public ParametersApiController(CurrenciesService service) {
this.service = service;
}

@Override
public ResponseEntity<List<Currency>> GetCurrencies(@PathVariable String theCurrencyCode) {
final List<Currency> currencies = service.getCurrencies(theCurrencyCode);
return new ResponseEntity<>(currencies, HttpStatus.OK);
}
}

关于java - Spring MVC @PathVariable 被视为 @RequestParam,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44439018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com