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

时间:2018-01-03 12:15:20

标签: spring-boot spring-data-jpa servlet-filters spring-rest

我有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?!

1 个答案:

答案 0 :(得分:1)

试试这个:

  1. 从控制器顶部删除@RequestMapping注释;
  2. @GetMapping注释替换为放入下一个注释的getAllGroceries()方法:

    @GetMapping(value = "/v1/data/groceries", produces = "application/json;UTF-8")<br>
    @ResponseBody