Home > Software engineering >  Should controller take "id" as PathVariable or should it take "page-id"
Should controller take "id" as PathVariable or should it take "page-id"

Time:10-23

We are trying to create SEO friendly roads. In this context, we decided to make changes to the url. E.g: /141(id) --> /example-page-141

I argue that we should get the "id" value as PathVariable on the back-end side. Another solution is to take "/example-page-141" as @PathVariable and find 141 in it. Which is the right solution?

  1. Solution

      @GetMapping("/get/{id}")
    public ResponseEntity<?> getProductDetail(@PathVariable Long id) 
    
        Product product = productService.getProductDetail(id);
    
        return new ResponseEntity<>(product, HttpStatus.OK);
    }
    
  2. Solution

     @GetMapping("/get/{id}")
     public ResponseEntity<?> getProductDetail(@PathVariable String id) {
    
    String[] bits = id.split("-");
    
    Long idLong = Long.valueOf(bits[bits.length-1]);
    
    Product product = productService.getProductDetail(idLong);
    
    return new ResponseEntity<>(product, HttpStatus.OK);
     }
    

What are the pros and cons of splitting from the backend or frontend?

CodePudding user response:

There is no black or white answer here as there is no real harm in using any of them.

But, if you are going with the approach#2, you will be dealing with the followings:

  1. You are tying the URL or the path param to have a fixed pattern i.e. x-x-x-<page_no>.
  2. Also, unnecessary string processing overhead on the backend.

Choice is yours! :)

CodePudding user response:

I would go with Option 1. Why? because it keeps the splitting logic in the frontend where it belongs. SEO is way more related to frontend than with backend, and as such, you should hide this complexity from the backend service.

One additional benefit is that if at some point in time the ID prefix changes, you can keep the changes in one place (frontend) and not in both frontend and backend which would require syncing the changes so that the backend service continued to be able to respond to the requests (of course you could have an alternative for this, but bottom line is that you would need to touch two codebases instead of a single one).

  • Related