我有一个@RestController
,如下所示。方法 getTrain(long)
应该为 URL http://localhost:8080/trains/1
选取,但它却选取 getTrains()
。其他 URL 按预期工作正常。我不确定我是否遗漏或不理解某些内容。我还看了Spring request mapping to a different method for a particular path variable value
这有点帮助。
要求: 1./trains [POST] - 添加火车 2./trains [GET] - 获取所有火车 3./trains/{trainId} - 通过id获取火车
@RestController
public class TrainController {
@Autowired
private TrainService trainService;
@RequestMapping(headers = { "Accept=application/json" }, method = RequestMethod.POST)
public TrainDto addTrain(@RequestBody TrainDto trainDto) throws Exception {
return trainService.addTrain(trainDto);
}
@RequestMapping(method = RequestMethod.GET)
public List<TrainDto> getTrains() throws Exception {
return trainService.getTrains();
}
@RequestMapping(value = "{trainId:\\d+}", method = RequestMethod.GET)
public TrainDto getTrain(@PathVariable("trainId") long trainId) throws Exception {
return trainService.getTrain(trainId);
}
}
最佳答案
您应该将value = "" 添加到映射请求中。看看这是否有效
@RestController public class TrainController {
@Autowired
private TrainService trainService;
@RequestMapping(value = "/trains",headers = { "Accept=application/json" }, method = RequestMethod.POST)
public TrainDto addTrain(@RequestBody TrainDto trainDto) throws Exception {
return trainService.addTrain(trainDto);
}
@RequestMapping(value = "/trains",method = RequestMethod.GET)
public List<TrainDto> getTrains() throws Exception {
return trainService.getTrains();
}
@RequestMapping(value = "/trains/{trainId}", method = RequestMethod.GET)
public TrainDto getTrain(@PathVariable("trainId") long trainId) throws Exception {
return trainService.getTrain(trainId);
}
}
或者你也可以这样做。
@RestController
@RequestMapping(TrainController.REQUEST_MAPPING_URL)
public class TrainController {
public static final String REQUEST_MAPPING_URL = "/trains";
@Autowired
private TrainService trainService;
@RequestMapping(value = "/",headers = { "Accept=application/json" }, method = RequestMethod.POST)
public TrainDto addTrain(@RequestBody TrainDto trainDto) throws Exception {
return trainService.addTrain(trainDto);
}
@RequestMapping(value = "/",method = RequestMethod.GET)
public List<TrainDto> getTrains() throws Exception {
return trainService.getTrains();
}
@RequestMapping(value = "/{trainId}", method = RequestMethod.GET)
public TrainDto getTrain(@PathVariable("trainId") long trainId) throws Exception {
return trainService.getTrain(trainId);
}
}
关于java - 使用 Path 变量为其他 URL 选择默认请求映射方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52089822/