繁体   English   中英

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

[英]Java “error”: “Not Found”, “message”: “No message available”,

我使用的是小型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"
}

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

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

@GetMapping("/stock/")

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

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

您需要像这样的映射:

@GetMapping("/stock")

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

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

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

因此,更新@GetMapping(“ / stock”)之类的映射。

学习愉快!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM