views:

83

answers:

3

Anyone know a decent Java libarary for HTML elements?

Ex if I want to create an img-element, I would go new Image(...)

The object should support the normal HTML functions/attributes, such as setting CSS or disable.

A: 

Try cobra.

craftsman
A: 

You're not specifying exactly why you need this, but sounds like you want to programmatically create a web site, specifically you want to have it component based so that each class encapsulates the function of corresponding tag.

There's two ways to go, one is premade component based web frameworks which is the preferred way since those things already have a lot of things thought out and implemented for you. For example Apache Wicket, Apache Tapestry and Google Web Toolkit are all component based just to name a few.

The other way you can approach this is to roll your own. In this case you most likely will lose a lot of the flexibility provided by the aforementioned frameworks but then again, you have a piece of code which will do exactly what you want. So, for rolling out your own for exactly the purpose you mentioned I'd do the following:

  1. Take any DOM manipulation library such as JDOM, DOM4J, XOM etc. You can of course use Java's native one too, but it's mostly a huge pain in the ass to use extensively.
  2. Write factory methods/wrapper classes for each individual tag, such as image. For example this could be the Image class content using JDOM:

.

public interface MyElement<T extends org.jdom.Content> {
    T getElement();
}

public class Image implements MyElement<org.jdom.Element> {

    private final String source;

    public Image(String source) {
        this.source = source;
    }


    public org.jdom.Element getElement() {
        return new Element("img").setAttribute("src", source);
    }
}

and in some component class describing the whole page you would then add and instance of this class to a list/tree structure and then just finally call the getElement() to get tag specific markup wherever applicable. Note that this is a lot harder than it sounds, mostly because of the required nested structure of XML.

Esko
+1  A: 

Jakarta ECS sounds like what you are looking for.

Mark