【问题标题】:Custom RepositoryRestController Mapping url throws 404 in spring-data-rest自定义 RepositoryRestController 映射 url 在 spring-data-rest 中抛出 404
【发布时间】:2016-11-08 06:40:31
【问题描述】:

我使用其对应的实体存储库编写了一个自定义RepositoryRestController。在此 url 上执行请求时,查询正在我的控制台中运行,但 url 返回 404。我还能够在日志中看到此 url 的 requestHandlerMapping。参考我下面的代码sn-p。

存储库:

   @RepositoryRestResource
    public interface FooRepository extends BaseRepository<Foo, Integer> {
    @RestResource(exported = false)
    List<Foo> findByName(String name);
    }

控制器:

@RepositoryRestController
public class FooResource {
@Aurowired
FooRepository fooRepository;

@Autowired
RestApiService restApiService;

@RequestMapping(value = "/foos/search/byApiName", method = GET)
public ResponseEntity<?> findByApiName(String name) {
List<String> apiNames = restApiService.getNameLike(name);
List<Foo> fooList = fooRepository.findByName(name);

List<String> fooNames = // list of names from fooList
...
System.out.println("FETCHING apiNames");
return apiNames;
}

当我执行以下 curl 命令时

curl -X GET http:localhost:8080/foos/search/byApiName

响应返回 404 错误。我不知道为什么。但他的打印输出语句正在控制台中打印。

@hat 我在这里做错了吗?

【问题讨论】:

  • Spring 中典型的 404 错误意味着您缺少上下文根。并且您在没有它的情况下调用该服务。尝试在端口号之后和/foos 之前添加它。通常是项目的名称。例如http://localhost:8080/SpringWeb/foos/search/byApiName

标签: controller spring-data-jpa spring-data-rest


【解决方案1】:

我建议您需要将 @ResponseBody 添加到您的方法或返回值(如 SDR 示例中的 http://docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.overriding-sdr-response-handlers)或将您的列表包装在 ResponseEntity 中。

不确定这些方法之间是否有任何区别,但都应该,如 Spring MVC 文档中所述:

"表示返回类型应该直接写入HTTP 响应主体(而不是放在模型中,或[被]解释为视图 名称)。”

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-responsebody

如果您打印了调试语句,但您得到了 404,那么似乎是后一种操作会发生。

@RequestMapping(value = "/foos/search/byApiName", method = GET)
@ResponseBody
public ResponseEntity<?> findByApiName(String name) {
    // ....
}

或者,

@RequestMapping(value = "/foos/search/byApiName", method = GET)
public @ResponseBody ResponseEntity<?> findByApiName(String name) {
   //....
}

或者,

@RequestMapping(value = "/foos/search/byApiName", method = GET)
public ResponseEntity<List<String>> findByApiName(String name) {
   //....

  return new ResponseEntity<List<String>>(fooNames, HttpStatus.OK);
}

【讨论】:

    【解决方案2】:

    发现控制器需要注解@RequestMapping,否则会被忽略。以下是我的代码:

    @RepositoryRestController
    @RequestMapping("/security")
    public class ...
    

    这对我有用。

    【讨论】:

      猜你喜欢
      • 2016-03-29
      • 2017-03-22
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      • 2013-05-21
      • 2018-04-18
      • 1970-01-01
      相关资源
      最近更新 更多