Over a million developers have joined DZone.

Using SiteMesh for page modification, not just decoration

DZone's Guide to

Using SiteMesh for page modification, not just decoration

Free Resource

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.


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}