Friday, September 17, 2010

Dynamic sitemap with annotations in Java

My current project is going fast. After a month of work we have 159 dynamic pages and this is going for sure up.

I was asked to provide a list of all the pages so the BA can specify what kind of security each of the pages should have.

I have built Site maps (or sitemaps) in different languages, both dynamically and by the time of release (pre published).

If you follow Spring @Controller and @RequestMapping annotations generating the site map is a piece of cake. Below is how to get a List of URLS:
...
import net.sourceforge.stripes.util.ResolverUtil;
...
private List<String> getSiteUrls(ControllerContext ctx, String controllersPackage) {
        List<String> urls = new ArrayList<String>();
        ResolverUtil<Object> resolver = new ResolverUtil<Object>();
        resolver.findAnnotated(Controller.class, controllersPackage);
        Set<Class<? extends Object>> controllerClasses = resolver.getClasses();
        for (Class<? extends Object> controller : controllerClasses) {
            String controllerRequestMapping = "";
            if(controller.isAnnotationPresent(RequestMapping.class)) {
                controllerRequestMapping = controller.getAnnotation(RequestMapping.class).value()[0];
                if(controllerRequestMapping.endsWith("/")) {
                    controllerRequestMapping = controllerRequestMapping.substring(0,controllerRequestMapping.length() - 1);
                }
                if(controllerRequestMapping.endsWith("/*")) {
                    controllerRequestMapping = controllerRequestMapping.substring(0,controllerRequestMapping.length() - 2);
                }
            }
            for (Method method : controller.getMethods()) {
                if (method.isAnnotationPresent(RequestMapping.class)) {
                    RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                    urls.add(controllerRequestMapping + requestMapping.value()[0]);
                }
            }
        }
        Collections.sort(urls);
        return urls;
}

Below is a JSP to render the results:
<%@ include file="/WEB-INF/jsp/includes.jsp"%>
<%@ include file="/WEB-INF/jsp/header.jsp"%>

<h2><spring:message  code="sitemap"/>:</h2>

<div id="global_error"><form:errors path="sitemap"
             cssClass="errors" /></div>

<c:forEach var="url" items="${urls}">
            <a href="<spring:url value="${url}"/>">${url}</a> <br/>
</c:forEach>

<%@ include file="/WEB-INF/jsp/footer.jsp"%>

No comments:

Followers