我正在尝试通过foodId获取一个食物对象,但我得到400错误代码,说必需的字符串参数'foodId'不存在。
这是我的控制器类:
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 /食品/ 5b08f8cee731e32c60e95aa8
5b08f8cee731e32c60e95aa8 是mongoDB提供的ID
请帮助。谢谢。
答案 0 :(得分:1)
foodId
"/{foodId}"
是@PathVariable
而非@RequestParam
正确的句柄方法应该是:
@RequestMapping(value = "/{foodId}",method = RequestMethod.GET)
public Object getFoodById(@PathVariable String foodId) {