hrishikeshp19
hrishikeshp19

Reputation: 9028

spring framework: correct way to handle multiple requestmappings with different pathvariables

I want to route multiple API endpoints to same controller method. But, I am using pathvariables in the url endpoints. For example:

    @RequestMapping(value = {"/{x}/{y}/article/{z1}", "/{x}/{y}/page/{z2}"}, method = RequestMethod.GET)
    @ResponseBody
    public Response getZ(HttpServletRequest request, HttpServletResponse response,
            @PathVariable("z1") String z1,
            @PathVariable("z2") String z2,
            @PathVariable("x") String x,
            @PathVariable("y") String y,
            @RequestParam(value = "A", required = true) String A) {
                return new Response();
            }

Is this appropriate way to handle multiple URLs with path variables? Is there any spring recommended way of doing this task?

Will z1 be null if z2 is present and vice versa?

Upvotes: 1

Views: 97

Answers (1)

Alaa Abuzaghleh
Alaa Abuzaghleh

Reputation: 1009

use

 @RequestMapping(value = {"/{x}/{y}/{cat:article|pages}/{zs:z1|z2}", method = RequestMethod.GET)
        @ResponseBody
         public Response getZ(HttpServletRequest request, HttpServletResponse response,@PathVariable("cat") String cat, @PathVariable("zs") String z){
        // you code here 
    }

as you see above that you can base many value for the same path variable, this will make it easy to handle this values in you code. hope this answer your question.

Upvotes: 1

Related Questions