skip to Main Content

I have an application with urls like site.com/article/1/title.htm

I have @RequestMapping /article/{id}/{title}.htm that server this request and gets the article.

What I am looking achieve is to have a url like site.com/title.htm but cant think of a way to do that using Spring MVC because I need id of the article. any ideas? Thanks in advance

2

Answers


  1. Chosen as BEST ANSWER

    There is no way send hidden id obviously, so it has to be done through a permalink of the article or simply via title, to achieve site.com/title.html you need to get rid of all the fixed bits by adding this request mapping rule:

    @RequestMapping(value = "/**/{articleTitle}.html"
    

    but to get the article you can obviously use id as its not there in the URL and have to work with that articleTitle or generate a permalink as suggested by @Sean above.


  2. When you create an article, you need to create the SEO-friendly URL also and persist it, along with the article. Now you need to have a repository method that allows you to retrieve articles by permalink, and a Spring MVC endpoint that calls that repository method.

    Using the title may not be a good idea, as the title is usually not URL-friendly, and may eventually be non-unique. But it is a good idea to use the title as the input for the permalink.

    Here’s a sample permalink algorithm:

    This is how the read path could look like:

    @Autowired
    private ArticleRepository ar;
    
    @RequestMapping(value="/article/{id}/{ignored}") @ResponseBody
    public Article getByIdAndIgnorePermalink(@PathVariable String id, @PathVariable String ignored){
        return ar.getById(id);
    }
    
    @RequestMapping(value="/article/{title}.html") @ResponseBody
    public Article getByPermalink(@PathVariable String permalink){
        return ar.getByPermalink(permalink);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search