4

When the user of my application creates a new page, she is asked to enter a 'Page Title' among other details. (e.g. she entered: "Page Title by Megan") The application saves the instance into db.

Now my requirement is that when anyone tries to access that page, the URL should be like:

www.websitename.com/pages/page-title-by-megan

I understand that with Spring MVC I can easily get the part "page-title-by-megan" by using something like:

@RequestMapping("/pages/{pageTitle}")
public String getPage(@PathVariable String pageTitle, Model model) {
    List<Pages> pages = pageService.getPages(pageTitle);
    model.addAttribute("pages", pages);
    return "pages";
}

But the problem is

Q1: To retrieve the relevant page, I need to store pageTitle "page-title-by-megan" along with the actual data in the DB? Is that the only trick to do this? Or there's a better way?

Q2: If that's the only way, how to effectively form a string like "page-title-by-megan" from "Page Title by Megan"? Again, is there a better approach?

Kindly guide. I would be very thankful.

LittleLebowski
  • 7,691
  • 13
  • 47
  • 72

1 Answers1

0

Q1: I think the only way is to store url to database as you said, with a unique restriction.

Q2: Assuming pageTitle contains the title entered by user, use this in your controller when submit is done:

String transformedPageTitle = pageTitle.toLowerCase().replace(" ", "-");
jelies
  • 9,110
  • 5
  • 50
  • 65
  • Thanks for the reply. But on second thought I'm wondering if it would be more effective if I just compare the url string with the page title from db by parsing the DB title at runtime everytime the page is called? What say? – LittleLebowski Sep 01 '12 at 10:39
  • Was wondering about it when Stack Overflow itself gave me a new idea. When we look at the URL of this page itself which is http://stackoverflow.com/questions/12226713/how-to-create-restful-urls-from-page-title-in-spring-mvc I can see that they have used an unique constraint in between the URL 12226713. So even if we type just http://stackoverflow.com/questions/12226713/ the page is rendered. Smart and works well with SEO too. What say? – LittleLebowski Sep 01 '12 at 10:53
  • That's correct, but but how does the browser shows http://stackoverflow.com/questions/1234567/this-is-sample in the address bar even if we pasted http://stackoverflow.com/questions/1234567/ ?? How is this achieved? – LittleLebowski Sep 01 '12 at 11:05
  • Because question is retrieved using only the key (1234567), and I think that a internal redirection to full URL is done once loaded. – jelies Sep 01 '12 at 11:09