public
Last active

Grails controller that automatically generates a sitemapfor your website.

  • Download Gist
SitemapController.groovy
Groovy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
/**
* A Sitemap controller that automatically generates sitemap.xml for a grails website.
*
* Be sure to notice the controllerNamesToExclude and actionsToExclude lists
*
* References:
* http://stackoverflow.com/questions/3748125/xml-sitemap-in-grails
* http://stackoverflow.com/questions/2956294/reading-out-all-actions-in-a-grails-controller
*
*/
package com.muhive
import groovy.xml.MarkupBuilder
import java.lang.reflect.Method
import grails.web.Action
 
class SitemapController {
 
def grailsApplication
 
/**
* If you want to exclude any controllers in the sitemap, especially Error controllers and services etc, include them in this array
*/
def controllerNamesToExclude = [ 'sitemap', 'error']
 
/**
* If you want to certain actions excluded, include them in this array. All actions with this name will be ignored
*/
def actionsToExclude = ['submitForm']
 
def index = {
StringWriter writer = new StringWriter()
MarkupBuilder mkp = new MarkupBuilder(writer)
mkp.mkp.xmlDeclaration(version: "1.0", encoding: "UTF-8")
mkp.urlset(xmlns: "http://www.sitemaps.org/schemas/sitemap/0.9",
'xmlns:xsi': "http://www.w3.org/2001/XMLSchema-instance",
'xsi:schemaLocation': "http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd") {
grailsApplication.controllerClasses.each { controller ->
Class controllerClass = controller.clazz
 
// skip controllers in plugins
if (controllerClass.name.startsWith('com.muhive') && !controllerNamesToExclude.contains(controller.logicalPropertyName)) {
String logicalControllerName = controller.logicalPropertyName
 
// get the actions defined as methods (Grails 2)
controllerClass.methods.each { Method method ->
 
if (method.getAnnotation(Action) && !actionsToExclude.contains(method.name)) {
mkp.url {
loc(g.createLink(absolute: true, controller: logicalControllerName, action: method.name))
changefreq('hourly')
priority(0.8)
}
}
}
}
}
}
render(text: writer.toString(),contentType: "text/xml", encoding: "UTF-8")
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.