skip to Main Content

We have a Spring MVC webapp and our product URL structure needs to be SEO friendly. Such as www.mydomain.com/{productname}. Every time we add a product to inventory, we want to have URL to display those product details.

We could not figure our how to generate dynamic URLs with Spring Controller Resource path.

Can someone please help us.

Would appreciate your help.

Thanks
Raj

2

Answers


  1. A Spring URL structure like http://www.mydomain.com/{productname} would seem to imply that ‘productname’ is always unique. If so, each product could have a property called ‘name’ or ‘productname’; this property could be used to retrieve the relevant product in your controller method. This will only work if every ‘productname’ is unique.

    Login or Signup to reply.
  2. What you are looking for is URI Template Patterns. In Spring MVC, @PathVariable annotation is used to bind an argument to the value of URI template variable.

    @RequestMapping(path="/{productname}", method=RequestMethod.GET)
    public String findProduct(@PathVariable String productname, Model model) {
        List<Product> product = productService.findProductsByName(productname);
        model.addAttribute("product", product);
        return "displayProduct";
    }
    

    Note that the service call returns List<Product> instead of one Product, since ideally, product name is not unique to one item. If you want the URI to identify exactly one product, make sure that product name is unique to one product only.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search