Skip to content

Instantly share code, notes, and snippets.

@ntung
Forked from itsmeritesh/SitemapController.groovy
Created October 8, 2022 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ntung/dc99afd7cd39279c7da14ea8acbcc786 to your computer and use it in GitHub Desktop.
Save ntung/dc99afd7cd39279c7da14ea8acbcc786 to your computer and use it in GitHub Desktop.
Grails controller that automatically generates a sitemapfor your website.
/**
* 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")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment