Spring REST服务没有找到GetMapping并返回HTML

问题描述 投票:0回答:1

我有一个Spring Boot app暴露了v1/data/groceries端点:

interface GroceryItemPersistor extends CrudRepository<GroceryItem, Long> {
    @Query('FROM grocery_items WHERE grocery_item_name = :name')
    GroceryItem findByName(@Param('name') String name)

    @Query('FROM grocery_items')
    List<GroceryItem> getAllGroceries()
}

@RestController
@RequestMapping('v1/data/groceries')
class GroceryItemResource {
    @Autowired
    GroceryItemPersistor groceryItemPersistor

    @GetMapping
    List<GroceryItem> getAllGroceries() {
        groceryItemPersistor.getAllGroceries()
    }

    ...
}

但是当我运行应用程序时(请参阅链接的自述文件)并发出以下curl语句:

curl -k -H "Content-Type: application/json" -X GET http://localhost:9200/v1/data/groceries

我认为这是卷曲的输出:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Error 404 Not Found</title>
</head>
<body><h2>HTTP ERROR 404</h2>
<p>Problem accessing /error. Reason:
<pre>    Not Found</pre></p>
</body>
</html>

然后,回到服务运行的终端,我看到以下控制台输出响应curl命令:

08:57:39.246 [qtp1939022383-16] WARN  o.s.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/error] in DispatcherServlet with name 'dispatcherServlet'
08:57:39.247 [qtp1939022383-16] WARN  o.e.j.server.handler.ErrorHandler - Error page loop /error

两个问题:

  • 我为什么要404?
  • 这是一个RESTful API ...为什么Spring会给我回HTML?!
spring-boot spring-data-jpa servlet-filters spring-rest
1个回答
1
投票

试试这个:

  1. 从控制器顶部删除@RequestMapping注释;
  2. @GetMapping注释替换为放入下一个注释的getAllGroceries()方法: @GetMapping(value = "/v1/data/groceries", produces = "application/json;UTF-8")<br> @ResponseBody
© www.soinside.com 2019 - 2024. All rights reserved.