Matt Raible has been building web applications for most of his adult life. He started tinkering with the web before Netscape 1.0 was even released. For the last 16 years, Matt has helped companies adopt open source technologies (Spring, Hibernate, Apache, Struts, Tapestry, Grails) and use them effectively. Matt has been a speaker at many conferences worldwide, including Devoxx, Jfokus, ÜberConf, No Fluff Just Stuff, and a host of others. Matt is a DZone MVB and is not an employee of DZone and has posted 149 posts at DZone. You can read more from them at their website. View Full User Profile

Using SiteMesh for page modification, not just decoration

  • submit to reddit

Did you know that SiteMesh contains an HTML Parser that can be used for page/HTML modificiation - not just decoration? In a mailing list message from May 2007, Joe Walnes explains how this is possible. In this post, Alex "the_mindstorm" asks if it's possible to add onclick event handlers to <a href> tags that are external to the current site. Here's how:

First, extend SiteMesh's HTML parser and add a new tag rule for processing <a> tags.

public class MyParser extends HTMLPageParser {

// override default rulest
protected void addUserDefinedRules(State html, PageBuilder page) {
super.addUserDefinedRules(html, page);

// Add a rule.
// Rules allow the parser to do custom things when encountering HTML tags.
html.addRule(new LinkRewritingRule()); // see below

class LinkRewritingRule extends BasicRule {

public LinkRewritingRule() {
super("a"); // Handles all <a> tags.

public void process(Tag tag) { // Called when parser encounters <a>
CustomTag newTag = new CustomTag(tag); // Allows tag modification

// modify href attribute
boolean caseSensitive = false; // allow HREF or href or HrEf
String oldHref = newTag.getAttributeValue("href", caseSensitive);
if (oldHref != null) {
String newHref = // do something;
newTag.setAttributeValue("href", caseSensitive, newHref);

// write the new tag bag to the page
newTag.writeTo (currentBuffer());

Then edit sitemesh.xml and update the <page-parser> tag to point to your new parser class. Pretty easy eh? Read Joe's full post for more tips and tricks.

Published at DZone with permission of Matt Raible, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)