1

The problem:

I’m trying to receive multiples resources in single Mapping of the controller. I need to take these resources and use to access the data in MongoDB.

Example:

If the access is in: mydomain.com/rootresource/datakey1/datakey2
I want to get the resources after rootresource for use to search data in MongoDB. The number of resources after rootresource is not a fixed.


My actual controller:

@RestController
@RequestMapping("users")
public class UserController {

    @Autowired
    private UserService service;

    @PostMapping
    public void create(@RequestBody UserCreateRequest request) {
        service.create(request.getAccess(), request.getPassword(), request.getData());
    }

    @GetMapping("/{access}")
    public UserDTO readByAccess(@PathVariable("access") String access) {
        return service.read(access);
    }

    @GetMapping("/{data:[\\/.]*}")
    public Document readByAccessAndData(@PathVariable("data") String data) {
        return null;
    }

}

My actual tentative is in readByAccessAndData function. When I call the url .../users/key1/key2 the received error is:

{
    "timestamp": "2019-09-21T22:22:31.262+0000",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/users/key1/key2"
}
Community
  • 1
  • 1
Isdeniel
  • 196
  • 10
  • So when you have a request: mydomain.com/rootresource/datakey1/datakey2 You want to query MangoDB to get user1 and user2 info right? I think to achieve this you’ll need to have a @RequestMapping(“rootresouce”) which I’m not seeing in the controller right now. – Dhruv Patel Sep 21 '19 at 23:53

2 Answers2

0

i suggest you do this:

    @GetMapping("keys:**/**")
public Document readByAccessAndData(HttpServletRequest request) {

String path = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();

String matchingPattern = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)
            .toString();

String arguments = new AntPathMatcher().extractPathWithinPattern(bestMatchingPattern, path);

arguments = arguments.replace("keys:","");//ignore the word 'keys:'.

String[] keys = arguments.split("/");

//now use keys to do whatever you want

//return whatever you want :)
}

i hope it is useful, please check this answer : @P.J.Meisch answer

if you try yourdomain.com/users/keys:k1/k2/k3
the array 'keys' will contain: ["k1","k2","k3"]

MuhammedH
  • 352
  • 4
  • 17
0

If the number of resources are going to grow so will the length of your URL.

In such cases you might want to consider sending the query data in the body of the request through a POST request.

padmanabhanm
  • 315
  • 3
  • 15