James Williams
LinkedInMastodonGithub

Handling Legacy URLs

Tags: General

Given that my blog had about 40 or so entries and dozens of links scattered out in the wild, it was fairly important that the existence of the new project didn't suddenly break all those links. So URL mapping was a prerequisite from day one.

Importing the old data

To avoid having to deal with the pecularities of making MySQL statements runnable on Apache Derby, I chose to export the data from the old blog as XML. Also, operating on XML allows your import to be implementation agnostic. After the export, I ran grails console and wrote a quick script to parse the XML, create objects, and persist them. One word of caution: The setId function on domain classes is merely a convenience method to satisfy the JavaBean spec. The objects will use whatever is the next available value in the sequence and not what you set. To get my entries in the proper order, I did a sort on the publish date. You should also be mindful of the dependencies of the objects and start with the object with no dependencies and move up the line. For me, that meant importing categories first, then entries, then comments(I had separately recreated users).

Having my entries added, I opened grails-app/conf/UrlMappings.groovy and tried to add the following:

"/blog/index.php?itemid=$id" {
    controller = xxxx
    action = xxxx
}

That failed miserably. The problem is that "?" has the context in Groovy to dereference if the variable is not null. After several tries, I figured out the correct solution is this:

"/blog/index.php" {
    controller = xxxxx
    action = xxxxx
}

The query string, of which itemid is a part, is represented in params so for the accompanying show action, we could use something like:

def show = {
    def entry
    if (params.itemid != null)
        entry = Entry.get(params.itemid)
    else entry = Entry.get(params.id)
    [entry : entry]
}