我试图通过 foodId 获取食物对象,但收到 400 错误代码,指出所需的字符串参数“foodId”不存在。
这是我的 Controller 类:
package com.quickmeal.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@RestController
@RequestMapping("/api/foods")
public class FoodController {
@Autowired
private FoodService foodService;
@RequestMapping(method = RequestMethod.POST)
public Food createFood(@RequestBody Food food) {
return foodService.createFood(food);
}
@RequestMapping(method = RequestMethod.GET)
public List<Food> listFood() {
return foodService.listFood();
}
@RequestMapping(value = "/{foodId}",method = RequestMethod.GET)
public Object getFoodById(@RequestParam String foodId) {
System.out.println("Testing..."+foodId);
return foodService.getFoodById(foodId);
}
}
我的服务等级:
package com.quickmeal.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.quickmeal.model.Food;
import com.quickmeal.repository.FoodRepository;
import com.quickmeal.service.FoodService;
@Service
public class FoodServiceImpl implements FoodService{
@Autowired
private FoodRepository foodRepository;
@Override
public Food createFood(Food food) {
return foodRepository.save(food);
}
@Override
public List<Food> listFood() {
return foodRepository.findAll();
}
@Override
public Object getFoodById(String foodId) {
return foodRepository.findById(foodId);
}
}
我的模型:
package com.quickmeal.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class Food {
@Id
private String foodId;
private String foodName;
private double foodPrice;
public String getFoodId() {
return foodId;
}
public void setFoodId(String foodId) {
this.foodId = foodId;
}
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this.foodName = foodName;
}
public double getFoodPrice() {
return foodPrice;
}
public void setFoodPrice(double foodPrice) {
this.foodPrice = foodPrice;
}
}
这是我的网址
本地主机:8080/api/foods/5b08f8cee731e32c60e95aa8
5b08f8cee731e32c60e95aa8是mongoDB给定的id
请帮忙。谢谢。
最佳答案
此路径中的
foodId
"/{foodId}"
是 @PathVariable
而不是 @RequestParam
正确的处理方法应该是:
@RequestMapping(value = "/{foodId}",method = RequestMethod.GET)
public Object getFoodById(@PathVariable String foodId) {
关于java - 所需的字符串参数 'foodId' 不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50543042/