Custom RepositoryRestController Mapping url throws

2019-07-28 04:44发布

问题:

I have written a custom RepositoryRestController using its corresponding entity repository. When performing request on this url, the query is running in my console, but the url returns 404. I also able to see the requestHandlerMapping for this url in logs. Refer my following code snippet.

Repository:

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

Controller:

@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;
}

When I execute the following curl command

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

the response returns 404 error. I don't know why. But he printout statement is printing in console.

@hat I am doing wrong here?

回答1:

I would suggest that you need to add the @ResponseBody to either your method or to the return value (as in the SDR example http://docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.overriding-sdr-response-handlers) or wrap your list in an ResponseEntity.

Not sure if there are any differences between these approaches but all should, as noted in the Spring MVC docs:

"indicate that the return type should be written straight to the HTTP response body (and not placed in a Model, or [be] interpreted as a view name)."

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

Given you debug statement prints but you get a 404 it would seem the latter action is what happens.

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

or,

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

or,

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

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


回答2:

I found out that the controller need the annotation @RequestMapping, otherwise it will be ignored. Below is my code:

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

This works for me.