【发布时间】:2017-11-10 08:43:20
【问题描述】:
我有一个 spring mvc API(XML 中的配置),里面有多个服务。但是当我尝试使用包含路径变量/{theCurrencyCode} 的@RequestMapping 添加服务时,创建的资源不是我所期望的。
我的预期:
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。
如何让我的@PathVariable 工作?
【问题讨论】:
-
这个问题好像已经讨论过了here
标签: java spring rest spring-mvc