我有一个spring mvc API(在XML中配置),里面有多个服务。但是,当我尝试添加包含路径变量@RequestMapping
的{{1}}的服务时,创建的资源不是我所期望的。
我的期望:
/{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);
}
Swagger UI确认了这一点,将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);
}
}
视为&#34;参数类型&#34; theCurrencyCode
代替query
。
如何让我的@PathVariable工作?
答案 0 :(得分:1)
您的方法实现中缺少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);
}
}
答案 1 :(得分:1)
带注释的方法参数未传递给所有实现。这就是为什么你需要重新声明它。
答案 2 :(得分:0)
将您的界面更改为:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="FirstCtrl">
<input type="number" style="font-family: sans-serif" ng-model="application.version" placeholder="Version..." required>
<button type="reset" ng-click="reset()">Clear </button>
</div>
您的路径变量名称和URL路径名称应匹配。无需在括号中指定参数名称。