Java“错误”:“未找到”,“消息”:“无可用消息”,

时间:2019-02-25 12:14:37

标签: java spring-boot curl

我使用一个小型的Spring应用程序,该数据库中的值很少,我想使用可变调用来检索它们。

API在这里

@RestController
@RequestMapping("/api/v1/products")
public class ProductAPI {

    private ProductService service;

    @Autowired
    public void setService(ProductService service) {
        this.service = service;
    }


@GetMapping("/stock/")
public ResponseEntity<Product> findById(@RequestParam("productId") String productId) {

    Product product = service.findById(productId).get();
    return ResponseEntity.of(Optional.of(product));
}

...........
}

服务电话

@Service
public class ProductService {


 private ProductRepository repository;

    @Autowired
    public void setProductRepository(ProductRepository productRepository) {
        this.repository = productRepository;
    }

    public Optional<Product> findById(String id) {

       return repository.findById(id);
    }
}

存储库类

@Repository
 public interface ProductRepository extends CrudRepository<Product, String>{


 }

使用cURL拨打电话时,我收到消息

   $ curl -X GET http://localhost:8080/api/v1/products/stock?productId=Product%20ID | jq
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   142    0   142    0     0    845      0 --:--:-- --:--:-- --:--:--   850
{
  "timestamp": "2019-02-25T12:19:31.797+0000",
  "status": 404,
  "error": "Not Found",
  "message": "No message available",
  "path": "/api/v1/products/stock"
}

我已正确插入数据库中的条目。这是什么问题?

2 个答案:

答案 0 :(得分:3)

因为您的映射中有多余的 /

@GetMapping("/stock/")

所以如果您想要这样的请求

  

卷曲-X GET   http://localhost:8080/api/v1/products/stock/?productId=Product%20ID

您需要像这样的映射

@GetMapping("/stock")

在您当前的版本中,右卷曲看起来像:

http://localhost:8080/api/v1/products/stock/?productId=Product%20ID

答案 1 :(得分:1)

由于您在控制器中清楚地将映射称为@GetMapping(“ / stock /”), 当您尝试通过路径/ stock访问资源时,显然没有这种映射。因此,您会发现404异常。

因此,像@GetMapping(“ / stock”)一样更新映射。

学习愉快!

相关问题