Using htmlKona
Version 3.0 incorporates support for the HTML 4.0 specification. Elements deprecated in HTML 4.0 are also deprecated (but still supported) in htmlKona version 3.0.
The htmlKona classes simplify the task of programmatically generating complex HTML documents. htmlKona, which in version 3.0 incorporates full support for all of HTML 4.0, as well as support for other scripting languages and many browser extensions, is useful both in interactive HTTP servlet environment and for periodic generation of static HTML pages. htmlKona is a powerful complement to other database- and event-related WebLogic products because of its ability to generate dynamic pages from queries. In a multitier environment, htmlKona can retrieve multimedia objects like audio clips and GIF/JPEG images from heterogeneous databases for incorporation into HTML pages. htmlKona creates class files that, when run against a Java-enabled HTTP server like WebLogic, produce HTML pages for a client browser. htmlKona provides an object-oriented interface to the HTML environment that allows you to format an HTML document with objects. In htmlKona, there are two basic types of objects: elements (derived from weblogic.html.HtmlElement) that are added to a page (derived from weblogic.html.WebPage). htmlKona treats a WebPage like a canvas. Instead of using a tagged syntax for mark up, you create a page object and add htmlKona elements to it. When completed, it is rendered by calling one of its output() methods. Features of htmlKona elements:
htmlKona tracks the development of the HTML specification. For more information about the HTML, we suggest the following sites:
Note that it is tough in general to tell what Netscape supports, at least from documentation on their website. Our best suggestions is to try it and see if it works in your browser. Microsoft has extensive support in IE 3 and 4 for Cascading Style Sheets, extended tables, and other HTML 4.0 elements. If you need more help, there are many links to HTML primers and reference manuals for every level of HTML author at yahoo. htmlKona API referenceClass java.lang.Object Class weblogic.html.Codeset Class weblogic.html.Cookie Class weblogic.html.EntityEscape Class javax.servlet.GenericServlet (implements javax.servlet.Servlet) Class javax.servlet.http.HttpServlet Interface weblogic.html.HtmlColor Class weblogic.html.HtmlElement Class weblogic.html.ElementWithAttributes Class weblogic.html.MultiPartElement Class weblogic.html.AppletElement Class weblogic.html.ColGroupElement Class weblogic.html.DefinitionList Class weblogic.html.DivElement Class weblogic.html.FieldsetElement Class weblogic.html.FormElement Class weblogic.html.FrameSetElement Class weblogic.html.ListElement Class weblogic.html.DirList Class weblogic.html.MenuList Class weblogic.html.OrderedList Class weblogic.html.UnorderedList Class weblogic.html.MapElement Class weblogic.html.NoFramesElement Class weblogic.html.NoScriptElement Class weblogic.html.SelectElement Class weblogic.html.SpanElement Class weblogic.html.TBodyElement Class weblogic.html.TFootElement Class weblogic.html.THeadElement Class weblogic.html.TableElement Class weblogic.html.TableRowElement Class weblogic.html.SinglePartElement Class weblogic.html.AcronymElement Class weblogic.html.AddressElement Class weblogic.html.AnchorElement Class weblogic.html.LinkElement Class weblogic.html.AreaElement Class weblogic.html.BaseElement Class weblogic.html.BaseFontElement Class weblogic.html.BigElement Class weblogic.html.BlockquoteElement Class weblogic.html.BodyElement Class weblogic.html.BoldElement Class weblogic.html.BreakElement Class weblogic.html.ButtonElement Class weblogic.html.CenteredElement Class weblogic.html.CiteElement Class weblogic.html.CodeElement Class weblogic.html.ColElement Class weblogic.html.CommentElement Class weblogic.html.DefineTermElement Class weblogic.html.DefinitionItem Class weblogic.html.EmbedElement Class weblogic.html.EmphasisElement Class weblogic.html.FontElement Class weblogic.html.FrameElement Class weblogic.html.HeadingElement Class weblogic.html.HorizontalRuleElement Class weblogic.html.ImageElement Class weblogic.html.InputElement Class weblogic.html.IsIndexElement Class weblogic.html.ItalicElement Class weblogic.html.KeyboardElement Class weblogic.html.LegendElement Class weblogic.html.LinkHeadElement Class weblogic.html.ListItem Class weblogic.html.LiteralElement Class weblogic.html.MetaElement Class weblogic.html.MultiColElement Class weblogic.html.ObjectElement Class weblogic.html.OptionElement Class weblogic.html.ParagraphElement Class weblogic.html.ParamElement Class weblogic.html.QElement Class weblogic.html.SampleElement Class weblogic.html.ScriptElement Class weblogic.html.SmallElement Class weblogic.html.SpacerElement Class weblogic.html.StrikeElement Class weblogic.html.StrongElement Class weblogic.html.StyleElement Class weblogic.html.SubscriptElement Class weblogic.html.SuperscriptElement Class weblogic.html.TableCaptionElement Class weblogic.html.TableDataElement Class weblogic.html.TableHeadingElement Class weblogic.html.TeletypeElement Class weblogic.html.TextAreaElement Class weblogic.html.TextFlowElement Class weblogic.html.TitleElement Class weblogic.html.UnderlineElement Class weblogic.html.VariableElement Class weblogic.html.FileElement Class weblogic.html.HtmlContainer Class weblogic.html.MarkupElement Class weblogic.html.AlignType Class weblogic.html.AnchorType Class weblogic.html.BorderstyleType Class weblogic.html.ClearType Class weblogic.html.FieldType Class weblogic.html.FrameType Class weblogic.html.MediaType Class weblogic.html.MimeType Class weblogic.html.RulesType Class weblogic.html.ScrollType Class weblogic.html.SpacerType Class weblogic.html.TextAlignType Class weblogic.html.WindowName Class weblogic.html.WrapType Class weblogic.html.StringElement Class java.lang.Throwable (implements java.io.Serializable) Class java.lang.Exception Class weblogic.html.HtmlException Class weblogic.html.WebPage Class weblogic.html.AudioPage Class weblogic.html.HtmlPage Class weblogic.html.ServletPage Class weblogic.html.ImagePage Class weblogic.html.PlainPage htmlKona Objects and their classesThe hierarchical arrangement of elements in htmlKona applies the structure and power of an object-oriented environment to the creation of HTML. There are two major descendencies in htmlKona: from WebPage and HtmlElement. The starting point for every htmlKona page is the creation of an htmlKona WebPage subclass -- mostly likely, you will be using htmlKona within an HTTP servlet, and you will create a ServletPage. After creating an htmlKona page, you add htmlKona HtmlElements to its head (with getHead()) or its body (with getBody()) containers, each of which is an weblogic.html.HtmlContainer. The elements are ordered and may be named inside one or more HtmlContainers, which is itself an HtmlElement. Here is a simple diagram: Pages: htmlKona's canvasAll htmlKona pages descend from the class weblogic.html.WebPage. There are five types of htmlKona WebPages:
htmlKona is most often used with HTTP servlets that subclass javax.servlet.http.HttpServlet.
All htmlKona elements descend from the class weblogic.html.HtmlElement. There are five general kinds of htmlKona Elements:
weblogic.html.ElementWithAttributes is further subclassed into two groups: weblogic.html.MultiPartElement and weblogic.html.SinglePartElement. These hierarchies are described on the API reference. ElementsWithAttributes includes most of the elements you will use to build a WebPage.
Classes in htmlKona can be organized by functionality or by a hierarchy of descendent relationships. In this portion of the documentation, the classes are grouped together functionally, that is, all of the elements you might need to create a list, for example, are discussed under the same topic.
Setting up a pageThe first step in using htmlKona to create a web page is to construct a WebPage object and, if needed, set its HEAD elements and other attributes. Then you build the document by adding HtmlElements to the WebPage. After you compile the htmlKona file, you place it in the proper directory on a Java-enabled server, restart the server (in some cases), and request the page from the server with a URL from your browser. There are five types of WebPages. They are all subclassed from the parent class weblogic.html.WebPage.
HtmlPages are of content-type "text/html", and are most commonly used. AudioPages and ImagePages are used to create multimedia HTML documents with Blob audio or visual images retrieved from a database. PlainPages are used for displaying unformatted text. ServletPages are subclassed from HtmlPage, but the content-type is not set. The only difference in these pages is the content-type that is passed to the HTTP server. There are methods in the WebPage superclass for setting content encoding, length, and type; for setting location, server, referer, and pragma; for setting expiration and last modified dates, and other attributes. There are methods in each type of WebPage to manipulate the types of HtmlElements you will manage. Creating an HtmlPageThe most commonly used WebPage object is a ServletPage, which is the subclass of HtmlPage that is used with Java-Servlet-API style HTTP servlets. An HtmlPage is the htmlKona canvas where you lay out a description of the page with HtmlElements; when you are finished, you call the output() method and the HTML for the page is automatically generated. The first step is to create an ServletPage: ServletPage hp = new ServletPage(); You can also construct the page with its title as a String argument. To set the codeset for a page, use the ServletPage constructor that takes a Codeset as an argument, for example: ServletPage sp = new ServletPage(new CodeSet("SJIS")); Adding the HEAD elementshtmlKona supports all of the HTML HEAD elements, which provide information to both the server and the browser. Add these to the page by calling the HtmlPage.getHead() method, and then using the addElement() methods: hp.getHead() .addElement(new TitleElement("htmlKona test2")) .addElement(new MetaElement(MetaElement.nameType, MetaElement.nameDescription, "WebLogic test meta element")) .addElement(new MetaElement(MetaElement.equivType, MetaElement.httpEquivExpires, new java.util.Date())) .addElement(new MetaElement(MetaElement.nameType, MetaElement.nameRobots, MetaElement.indexNoFollow)) .addElement(new LinkHeadElement(LinkHeadElement.relTag, LinkHeadElement.relHome, "www.weblogic.com", "WebLogic Home"));The htmlKona classes for HEAD elements are:
Adding attributes to the BODY elementAfter setting up the HEAD portion of the page, call the HtmlPage.getBodyElement() method to set attributes for the BODY elements. You set attributes using the setAttribute() method from the BodyElement class, which also provides a set of constants for the current BODY attributes. hp.getBodyElement() .setAttribute(BodyElement.bgColor, "#FFFFFF") .setAttribute(BodyElement.backgroundImg, "images/wtbkg.gif") .setAttribute(BodyElement.linkColor, HtmlColor.fuchsia) .setAttribute(BodyElement.aLinkColor, "#080808") .setAttribute(BodyElement.vLinkColor, "#808080"); Also supported are ONLOAD and ONUNLOAD attributes for scripts. Note that the 16 HTML color names are encapsulated in the weblogic.html.HtmlColor class. All htmlKona operations that involve a color also provide methods that take a java.awt.Color object as an argument. Building the document bodyOnce you have created an HtmlPage, added its HEAD elements, and set its BODY attributes, you can add HtmlElements to it with various addElement() methods. When you are finished, use one of the HtmlPage.output() methods to output the page to the proper source. ExampleHere is a very simple example of the complete code from a class written using htmlKona. This class is written with a main, to allow you to output the HTML without running the class against a Java-enabled server. import java.io.*; import weblogic.html.*; public class helloworld { public static void main(String argv[]) throws HtmlException, IOException { HtmlPage hp = new HtmlPage(); hp.getHead() .addElement(new TitleElement("The Hello World Page")); hp.getBodyElement() .setAttribute(BodyElement.bgColor, HtmlColor.white) .setAttribute(BodyElement.backgroundImg, "images/mylogo.gif"); hp.getBody() .addElement(MarkupElement.HorizontalRule) .addElement(new StringElement("Hello World!") .asBoldElement()) .addElement(MarkupElement.HorizontalRule); hp.output(); } }Here is what the HTML for this example will look like: Hello World! To test this example:
Other page-defining elementsYou can also create frames with htmlKona. Not all browsers will display frames. htmlKona provides extensive support for frames, including extensions in Netscape 3.0x. The HTML specification divides markup elements into two general classes: those that cause paragraph breaks (block-level), and those that do not (text-level, both physical and logical elements). htmlKona makes an additional distinction between block-level elements that have multiple parts -- like lists and forms -- and those that contain only text or other text-level kinds of elements. Discussion in this document is arranged to track as closely as possible the organization that HTML itself uses, so that if you are familiar with HTML, you will find htmlKona easy to understand. Consequently, we first discuss simple block-level elements, then physical and logical elements, followed by more complex elements like tables and forms. Simple, single-part block-level elements in htmlKona include the following:
hp.getBody() .addElement(new HeadingElement("Breaking New Ground", 2)) .addElement(new HorizontalRuleElement()); Many of these elements, in particular those that do not require an ending tag, are encapsulated in the general htmlKona class, weblogic.html.MarkupElement. For example, you can insert a horizontal rule into your HtmlPage in two ways: hp.getBody() .addElement(new HorizontalRuleElement() .setAlign(AlignType.center) .setWidth("50%"))or merely hp.addElement(MarkupElement.HorizontalRule) The first way, by creating a HorizontalRule object, allows you to use other methods in the HorizontalRule class to set additional attributes for the object. The second way provides a convenient short-cut for adding a markup element to your page, if you do not intend to set any further attributes. Setting physical and logical attributesClasses for physical and logical attributes:
In this example, we create a FontElement, and set its size and color: hp.getBody() .addElement(new FontElement(5, HtmlColor.red, "To the Stars!"));We can also cast another HtmlElement as a FontElement in order to use methods in the FontElement class on it. For example, here we center the element and set its color. hp.getBody() .addElement(new HeadingElement(filename, 2) .setAlign(TextAlignType.center) .asFontElement("3", HtmlColor.fuchsia)); Other text-level classesThere are two other text-level classes that do not cause paragraph breaks and are not specifically a physical or logical element:
AddressElementThe AddressElement class identifies the author of the page, and also has a constructor for creating a hyperlink for contact information. It is often displayed in italic text. For example: hp.getBody() .addElement(new AddressElement("http://www.weblogic.com", "BEA Systems Inc."));If you use an AddressElement to add a multiline address to a page, you should add a BreakElement (or a MarkupElement.Break) between each line. For example: HtmlContainer ae = new HtmlContainer(); ae.addElement("BEA Systems Inc.") .addElement(MarkupElement.Break) .addElement("180 Montgomery Street, Suite 1240") .addElement(MarkupElement.Break) .addElement("San Francisco, California 94104") .addElement(MarkupElement.Break); hp.getBody() .addElement(new AddressElement(ae)); SpacerElementThe SpacerElement (supported in some browsers) allows you to set horizontal, vertical, or block whitespace between objects on a page. Either the size attribute, or the width, height, and alignment attributes are set. A SpacerElement constructor may use a weblogic.html.SpacerType object to set the SpacerElement's type attribute. Encapsulation classeshtmlKona provides several classes for encapsulating certain kinds of attributes that are used often by other objects. Except for the Codeset and the HtmlColor interface, encapsulation classes are all subclassed from MarkupElement. Classes that are in general use, like AlignType and HtmlColor are discussed here; other classes that are associated with a particular element or set of elements are discussed with that element at other (linked) places in this document. Encapsulation classes:
CodesetUse a weblogic.html.Codeset object as an argument to either ServletPage or HtmlPage to set the document's codeset. The default codeset if unset is "8859_1", which is the Latin character set used by English, German, and the Romance languages. An example: ServletPage sp = new ServletPage(new Codeset("SJIS"));
which sets the codeset to Shift-JIS, Japanese. Codesets are defined in
the JavaSoft internationalization specification documents at JavaSoft.
Use a weblogic.html.AlignType object as an argument to the various setAlign() methods to set alignment of HtmlElements like AppletElement, HorizontalRuleElement, and the various Table*Elements. The variables in this class set the alignment. (Note that TextAlignType, not AlignType, is used to align text in a container.) Here is an example of using an AlignType object to set alignment for parts of a table: TableElement table = new TableElement(); table.setCaption(new TableCaptionElement("Usage Statistics") .setAlign(AlignType.bottom)) .setBorder(1) .addElement(new TableRowElement() .addElement(new TableDataElement(reg.getID()) .setVAlign(AlignType.top)) .addElement(new TableDataElement( new TableElement(reg.getMain()) .setCaption( new BoldElement("N1")) .setBorder(1)) .setVAlign(AlignType.top) .setAlign(AlignType.right))); TextAlignType
A weblogic.html.TextAlignType object is used
to set the alignment for the text contents of HtmlElements like
ParagraphElement, DivElement, and HeadingElement. The variables in
this class include center, justify, left, and right. Use TextAlignType
objects as arguments for the setAlign() methods of text
containers.
A weblogic.html.ClearType
object sets the HTML CLEAR attribute, which moves an HtmlElement
(BreakElement or a DivElement) down unconditionally after a figure or
a table, rather than flowing around the figure or table.
The 16 HTML color names are encapsulated in the class weblogic.html.HtmlColor as String elements, so
that methods and constructors that take a color as an argument can use
either a variable from the HtmlColor class (like HtmlColor.white), or
can use the six-letter string hex RGB value (like "#FFFFFF"). Note
that there are usually identical methods and constructors that also
take a java.awt.Color object as an argument.
Use a weblogic.html.WindowName object to set a target window for a link with the setTarget() methods in various htmlKona classes. Variables in the class are analogous to the HTML magic target names _blank, _parent, _self, and _top. Targets for links are often used with frames, images and image maps, and anchor elements. Classes for creating anchors: Use a weblogic.html.AnchorElement object to set hypertext links in your HtmlPage. (It supersedes an older class, LinkElement, that is still supported for backwards compatibility.) There are two real uses for anchors; one use is with an HREF attribute to set a hyperlink to another document or an internal link, and the other use is with a NAME attribute to identify an internal link. For instance, this paragraph is marked with the anchor <A NAME="anchorelementdef">, which allows you to jump to this paragraph from a link within this document that is marked with the anchor <A HREF=#anchorelementdef>. Consequently, the constructors for this class are of two types, one set that is primarily for hyperlinking text with an HREF attribute, and the other that is primarily for marking text with a NAME attribute. The constructors in this class also use objects from the encapsulated class weblogic.html.AnchorType as arguments for the constructor, to remove the ambiguity in using simple Strings for the HREF and NAME attributes. You can, in fact, use both the HREF and NAME attributes in the same anchor, to provide an internal destination, and also to link to another document. If you view the source of this paragraph, you will see that the hyperlink above for the AnchorType class name uses both attributes. You can also use a weblogic.html.WindowName object in one of the AnchorElement constructors to direct the specified URL into a different browser window. Here are some AnchorElement uses: hp.getBody() .addElement( new AnchorElement("http://www.acme.com/copyright.html", "© 1996, Acme Inc.")) .addElement( new AnchorElement(AnchorType.href, "http://www.acme.com/copyright.html", "© 1996, Acme Inc.")) .addElement( new AnchorElement(AnchorType.name, "topic1", "The most important topic")) .addElement( new AnchorElement("http://www.acme.com/copyright.html", "© 1996, Acme Inc.", WindowName.parent)); You can also set an internal NAME anchor in with the HtmlPage.asAnchorElement() method, as in this example: hp.getBody() .addElement(new StringElement("This text is an " + "internal anchor") .asAnchorElement("anchor1")) .addElement(new StringElement(" in this document.")); Using listsThere are two types of lists: DefinitionLists and ListElements. htmlKona supports several subclasses of ListElement, including OrderedList and UnorderedList, MenuList, and DirList. Note that HTML 3.2 deprecates both MenuList and DirList to be replaced by the more general UnorderedList. htmlKona supports these for backwards compatibility, but not all browsers may continue to display such lists. Classes for lists:
DefinitionListDefinitionLists are made up of DefinitionItems, which are added with the addElement() method. A DefinitionItem has two parts, a term and a definition. The DefinitionItems in a List are accessible by index position. ListElementThere are several kinds of ListElements that correspond to HTML ordered and unordered lists. A ListElement is made up of ListItems or strings. The items in a list are accessible by index position. htmlKona supports several additional attributes for list elements. Here is an example of building an unordered list: UnorderedList ul = new UnorderedList(); ul.setType(UnorderedList.circle) .addElement(new ListItem("$500")) .addElement(new ListItem("$250")) .addElement(new ListItem("$100"));This produces the following output:
htmlKona supports the type attribute for both ordered and unordered lists. Valid types for each kind of list are encapsulated as String constants in each class. htmlKona also supports the start argument for OrderedLists and for ListItems added to OrderedLists. This allows you to control the numbering sequence, as in this example: OrderedList ol = new OrderedList(); ol.setType(OrderedList.largeRoman) .setStart(13) .addElement("500") .addElement("600") .addElement("435") .addElement(new ListItem("250") .setType(OrderedList.smallRoman) .setValue("7")) .addElement("195") .addElement("100");This would be displayed as follows:
Classes for image management:
Use the ImageElement to place an inline image on an HtmlPage. For example:hp.getBody() .addElement(new ImageElement("http://website/images/bar.gif")); The ImageElement class has methods for setting height, width, Hspace, Vspace, source, border, alternate text, and alignment for an ImageElement. In addition, htmlKona supports both serverside and client-side image maps, for which there is an additional ImageElement methods, setUseMap() and setIsMap(boolean) methods. You can also use a weblogic.html.ImagePage to display an image retrieved as a byte array (byte[]) from a database.
Serverside image maps run a CGI script on the server to respond to mouse events over regions of an image. The additional attribute ISMAP is required for an ImageElement to act as an image map. To create a serverside image map, you should use an ImageElement as an argument for an AnchorElement that sets the CGI script as its URL. For example: // Create the ImageElement ImageElement ie = new ImageElement("http://www.weblogic.com/images/h.gif"); // Set the ISMAP attribute ie.setIsMap(true); hp.getBody() // Construct an AnchorElement with the CGI script as its URL // and the ImageElement as its display .addElement(new AnchorElement("/cgi-bin/imagemap", ie)); Several browsers now also support client-side image maps, which allow you to use local information associated with an image instead of serverside information (a serverside image map). htmlKona supports client-side image maps, but you should make sure the browser intended for display supports them. Classes for client-side image maps:
A MapElement, which is constructed by setting its name, is a multipart element that is created by adding AreaElements to it. Use an AreaElement to set coordinates for each "hotzone" on the image map. An AreaElement is used to set coordinates for a region of the image that is mapped to a particular URL. Valid region shapes, encapsulated (as String constants) in the AreaElement class, or java.awt.Rectangle and java.awt.Polygon, can be used with the constructors and methods. The class contains other methods for setting coordinates and URLs. Note that setting the ALT attribute is highly recommended, to give the user some information when the image is not present or not displayed. This example shows how to build a simple MapElement that provides links to help from a screen image. First we set up some arrays that will be used in some of the constructors; then we add an ImageElement; and finally we create the MapElement. int[] xcoords = {353, 475, 353}; int[] ycoords = {116, 163, 163}; int ncoords = 3; int[] rectcoords = {353, 33, 475, 53}; hp.getBody() // Create a new ImageElement and call its setUseMap() method .addElement( new ImageElement( "http://www.weblogic.com/images/ipscreen.gif") .setAlign(AlignType.center) .setUseMap("#MyMap", true)) // Create a new MapElement .addElement(new MapElement("MyMap") // Add an AreaElement. This one uses an // array of ints as its coordinates. .addElement(new AreaElement() .setShape(AreaElement.rectangle) .setHref("htmlimgmap.html#ok") .setCoordinates(rectcoords)) // This constructor takes a string //as its coordinates .addElement(new AreaElement(AreaElement.rectangle, "353, 60, 475, 82", "htmlimgmap.html#cancel")) // This constructor takes an // AWT Rectangle as an argument .addElement(new AreaElement(new java.awt.Rectangle( 353,88,475,100), "htmlimgmap.html#dns")) // This constructor takes an AWT Polygon // as an argument .addElement( new AreaElement(new java.awt.Polygon(xcoords, ycoords, ncoords), "htmlimgmap.html#advanced")) .addElement( new AreaElement(AreaElement.circle, "220, 193, 40", "htmlimgmap.html#circle"))); hp.output(); Here is the output of this example:
Classes for frames:
FrameElementUse one FrameElement for each frame on the page. There are methods in this class for setting frame margins, the name and source for the target window, the scrolling behavior, and whether or not the frame can be resized. Note that if you set the noresize attribute of a frame to true, other frames on the page with which it shares a side will also automatically be set to noresize. htmlKona also supports browser extensions for setting bordercolor and frameborder, as well as the onLoad and onUnload attributes for using scripts. FrameSetElementUse a FrameSetElement as a container for FrameElements to design an HTML page that uses frames. Construct a new FrameSetElement and then use its addElement() methods to add FrameElements to it. Each FrameSetElement may contain two FrameElements or other FrameSetElements. You can use multiple FrameSetElements to position frames within frames. Use the setCols() and setRows() to divide the screen size (in pixels or percentage) between the two objects contained in the FrameSetElement. htmlKona also supports browser extensions for bordercolor, frameborder, and border attributes. The elements in a FrameSetElement are accessible by integer index. NoFramesElementUse a NoFramesElement to set the contents of a page with frames that should be displayed if the browser cannot display frames. ScrollTypeThe ScrollType class encapsulates valid scrolling attributes for frames in htmlKona. Use a ScrollType to set the scrolling characteristics for FrameElement. You use a ScrollType object as an argument for the setScrolling() method in the FrameElement class. ExampleIn this example, we construct one FrameSetElement fs and set the size of its panels to 30% and 70% of the page. We set the smaller side of the FrameSetElement to the FrameElement Frame1. Then we construct another FrameSetElement fs2 containing two FrameElements (Frame2 and Frame3). We add the entire FrameSetElement fs2 to the first FrameSetElement as the larger side of the page. String base = "/ns-home/frameExample"; FrameSetElement fs = new FrameSetElement() .setRows("30%,70%") .setBorderColor(HtmlColor.fuchsia) .setFrameBorder(true); fs1.addElement(new FrameElement().setName("Frame1") .setSource(base + "?name=Frame1") .setScrolling(ScrollType.no)); FrameSetElement fs2 = new FrameSetElement() .setCols("50%,50%"); fs2.addElement(new FrameElement().setName("Frame2") .setSource(base + "?name=Frame2")); fs2.addElement(new FrameElement().setName("Frame3") .setSource(base + "?name=Frame3")); fs1.addElement(fs2); hp.setFrameSetElement(fs1); Classes for tables:
The chief table object in htmlKona is the TableElement. Construct the TableElement, sets its caption and attributes, and then add rows of headings or data to it. TableElements are generically composed of TableRowElements, which are generically composed of TableDataElements, or TableHeadingElements, a special kind of TableDataElement. A TableDataElement corresponds to a single table cell; you can set the contents of a TableDataCell as well, after it is constructed. TableRowElements and TableDataElements can also be built with strings or with other HtmlElements. For instance, you can use an ImageElement to display an image in the cell of a table. You use TableCaptionElements to set a caption for the table. You can also use a dbKona DataSet to construct a TableElement. Using htmlKona to display data from a dbKona DataSet is convenient because the Schema object associated with a DataSet can automatically supply the structure of a TableElement when the TableElement is constructed. Likewise, you can construct a TableRowElement with a single Record from a dbKona DataSet. The TableElement class has methods for adding, getting, and setting rows and cells. Rows and cells in a TableElement are accessible by index position. The TableElement class has also methods for setting attributes such as border, caption, cellpadding, cellspacing, and width. htmlKona supports certain browser extensions for tables like background color and image attributes, and Mosaic's BORDERSTYLE (with encapsulated constants from the weblogic.html.BorderstyleType class) attribute. It also supports FRAME and RULES attributes that have been proposed for adoption in HTML3.5; use encapsulated constants from the weblogic.html.FrameType and weblogic.html.RulesType classes to set these attributes. Set alignment for table elements with an AlignType objects. ExampleThis example shows how to construct two tables, one nested inside the other. Note that in some cases we construct the TableRowElement by adding arbitrary HtmlElements; in other cases, we add a TableDataElement. You can use any HtmlElement as an argument to TableRowElement.addElement(), but if you want to set any characteristics on the table cells, such as alignment or background color, you must add the cell as a TableDataElement, and use methods in that class to set cell characteristics. // Create the table and set attributes and caption, // which will display at the bottom of the // table in an italic font TableElement tab = new TableElement() .setBorder(1) .setCellPadding(5) .setWidth("50%") .setCaption(new TableCaptionElement( new ItalicElement("Fall Registration Schedule")) .setAlign(AlignType.bottom)); // Add a table row and build it with table headings. // Note that we set the first table heading as an // internal anchor by creating it as an AnchorElement. // We also set a different background // color for the second column heading. tab.addElement(new TableRowElement() .addElement( new TableHeadingElement(new AnchorElement( AnchorType.name, "topic", "Topic"))) .addElement(new TableHeadingElement("Scheduled") .setBgColor("#A93B6F"))); // Add a second row. In the first column we call // a method to get an ID, and the second column // we make a nested table. We align the nested // table at the top of the cell by calling // the setVAlign() method on the TableDataElement. tab.addElement(new TableRowElement() .addElement(new TableDataElement(reg.getID()) .setVAlign(AlignType.top)) // The nested table is the output of a // method that retrieves a dbKona DataSet .addElement(new TableDataElement( new TableElement(reg.getMain()) .setCaption(new BoldElement("N1")) .setBorder(1)) .setVAlign(AlignType.top))); // Add a row with simple strings tab.addElement(new TableRowElement() .addElement("RegID 609E") .addElement("N2 - 10AM MWF")); // Finally, add the table as a centered // element to the HtmlPage. hp.getBody() .addElement(new CenteredElement(tab)); The output for this example would look something like this, depending upon the contents of the embedded table:
Classes for forms:
As in HTML, FormElements can be nested inside TableElements to make it easy to lay out the form. When you use a TableElement to set up the layout for a form, make sure you are operating on the TableRowElements or TableDataElements when setting table attributes, and not on the contents of your FormElement. (This is further illustrated in the example code below.) The type of InputElement is set in the constructor with a weblogic.html.FieldType object. The FieldType class encapsulates all of the valid types of HTML input elements, including checkbox, textarea, radio, submit buttons, etc. The class also supports the following:
A SelectElement, which creates a dropdown- or scrolling-type box of selectable items on a form, is made up of OptionElements. You construct a SelectElement and use the addElement() methods to add options, which can be strings or OptionElements. Use an OptionElement if you will need to use any of the methods in the OptionElement class to set attributes. An OptionElement has a Value that is not displayed, as well as a string that is displayed. TextAreaElements are multiline text boxes for user input. You can present the user with some default text in the textbox with the setContent() method. (For a single-line textbox, use an InputElement of FieldType.text.) Set height and width of the textbox with the setRows() and setCols() methods. htmlKona also supports extensions like the attributes ONFOCUS, ONBLUR, ONSELECT, and ONCHANGE. You set the text-wrap characteristics for a TextAreaElement with a WrapType object. Use the TextAreaElement.setWrap() method with a WrapType object to set the text wrap to off, virtual, or physical wrap. Getting form dataWhen you process your htmlKona FormElement against a Java-enabled server, you must retrieve information entered by the user with the Submit button, i.e., the Common Gateway Interface (CGI) variables. Very simply, when the user presses a Submit button on your form, the same class that displayed the new form is invoked again, this time retrieving and using information that the user entered on the form. As a rule, CGI variables are referenced to the NAME attribute of the FormElement; the contents of the variable depend upon the type of input element, that is, a textarea element will return a string and a select element will return the index position of the selected option.With both Java Server and Netscape servers, CGI variables are stored as a Hashtable object, and you use the get() methods to retrieve the contents of the variables. The examples that follow show real-life uses for serverside Java against both Java Server and Netscape servers, including implementation details for Java Server and Netscape. ExampleHere is an example that shows the several steps involved in creating a FormElement. In this example, we also use a TableElement to line up the user input areas on the form. There are six steps shown in this example:
import weblogic.html.*; import java.io.*; public class myform { public static void main(String argv[]) throws HtmlException, IOException { // Create a page and set its title HtmlPage hp = new HtmlPage(); hp.getHead() .addElement(new TitleElement("Creating a Form with htmlKona")); // Create a form FormElement form = new FormElement("/servlet/myform", "POST"); // Create a table and use it to organize form elements TableElement tab = new TableElement().setBorder(0); // Add input elements and labels for the form // as rows in the table tab.addElement(new TableRowElement() .addElement(new TableHeadingElement("Your name")) .addElement(new TableHeadingElement("Password")) .addElement("")); tab.addElement(new TableRowElement() .addElement(new InputElement("namefield", FieldType.text) .setValue("Your name") .setSize(20) .setMaxlen(30)) .addElement(new InputElement("password", FieldType.password))) .addElement(new TableRowElement() .addElement(new TableDataElement( new InputElement("submit", FieldType.submit) .setValue("Check my account")) .setColspan(2))); // Add a TextAreaElement and the table to the form form.addElement(new TextAreaElement("notes", "Enter your comments") .setCols(30)) .addElement(tab); // Add the form to the page hp.getBody() .addElement(MarkupElement.HorizontalRule) .addElement(new HeadingElement("Feedback Form", 2)) .addElement(form) .addElement(MarkupElement.HorizontalRule); hp.output(); } } Here is how this form will look: Adding a script to a pageClasses for use with scripts:
Note that script functions are called from event handlers within the page that can be set with methods in many htmlKona classes for attributes ONBLUR, ONCHANGE, ONLOAD, ONUNLOAD, etc. Using a ScriptElementA ScriptElement can be added to the head portion of a document, after calling the HtmlPage.getHead() method. A ScriptElement can also be added with the addElement() methods in several classes.ExampleThis Netscape example shows a simple JavaScript script to be executed as part of a form with the GET action. (Note that Netscape serverside Java doesn't support package names.) The ScriptElement is added after calling the HtmlPage.getHead() method. This example uses a ScriptElement to evaluate an expression and return an answer: import netscape.server.applet.HttpApplet; import java.io.*; import weblogic.html.*; public class adder extends HttpApplet { public synchronized void run() throws IOException { try { // Housekeeping for a Netscape serverside // Java class this.returnNormalResponse("text/html"); // Construct the page ServletPage hp = new ServletPage("Example 2d"); // Construct a FormElement for user input FormElement form = new FormElement("", "GET"); // Use a table to line up the elements on the form // and add it to the form TableElement tab = new TableElement(); form.addElement(tab); // Populate the table with InputElements. We create // a row with 3 cells tab.addElement(new TableRowElement() .addElement(new InputElement("input") .setValue("9 + 3") .setSize(20) .setMaxlen(20)) .addElement(new InputElement("button1", FieldType.button) .setValue("Evaluate") .setOnClick("compute(this.form)")) .addElement(new InputElement("answer") .setValue("The answer is: 12") .setSize(20) .setMaxlen(20))); // Use the getBodyElement() method to set // attributes for the BODY tag hp.getBodyElement() .setAttribute(BodyElement.bgColor, HtmlColor.white); // Call getBody() to add various elements to // the page, including the ScriptElement. hp.getBody() .addElement(MarkupElement.HorizontalRule) .addElement( new ScriptElement( "document.write(\"This is a simple JavaScript " + "expression evaluator.\")")) .addElement(MarkupElement.BeginParagraph) .addElement( new ScriptElement( "document.write(\"Enter an expression on the " + "left and click on Evaluate.\")")) // Note that we use "\n" to force newlines in the // ScriptElement, which makes the JavaScript // line up nicely. .addElement(new ScriptElement( "function compute(form) {\n" + " if (confirm(\"Evaluate Expression \" + form.input.value + \" ?\"))\n" + " form.answer.value = \"The answer is: \" + eval(form.input.value);\n" + " else\n" + " alert(\"Try again and choose OK.\");\n" + "}")) // Finally, add the form to the page .addElement(form) .addElement(MarkupElement.HorizontalRule); // We invoke the ServletPage.output() method with the // results of HttpApplet's getOutputStream() method hp.output(getOutputStream()); } catch (Exception e) { e.printStackTrace()); } } }
The documentation for the Netscape HttpApplet classes can be found at Netscape's
DevCon site.
AppletElementUse an AppletElement to set attributes for the applet and to describe where it should be placed on the htmlKona page. The three parameters required in an applet element, the CODE, WIDTH, and HEIGHT attributes, are used in the constructors. There are also methods in the AppletElement class for setting alignment of the applet, the code base (URI), name, HSPACE, VSPACE, and alternate text for the applet.In addition, htmlKona supports the ARCHIVE browser extension that lets you specify a .zip file to be downloaded to the user's disk to speed applet loading. Note that the .zip file is looked for relative to the CODEBASE for the applet, and that the .zip file must not be compressed. Classes needed by the applet that are not included in the .zip file will be searched for by traditional methods. htmlKona also supports the HTML3.2 TEXTFLOW element within the applet tag, which is used to set alternate text that will be displayed if the applet cannot load or run. Note that the HTML specifications 2.0 and later require that you set alternate text for your applet. You may use the AppletElement.setAlt() method if desired, or you may add a TextFlowElement object with AppletElement.addElement(). The latter is recommended. To set parameters for the applet, add ParamElements to the AppletElement with the AppletElement.addElement() method. A ParamElement is a name/value pair. ParamElements added to an AppletElement are accessible by index position with the getElementAt() method. Note that parameter names are case sensitive. Use an AlignType object as an argument for the AppletElement object to set the applet's alignment on the page. AlignType objects are also used to set alignment for other objects. ExampleThis example shows a Java Server-style servlet that loads the BlinkingText element from JavaSoft. This class file can be found in the distribution in weblogic/examples/htmlkona/. The showException method is part of another class in the distribution (defaults). For more information on running this and other classes in the examples, check How to run these examples.package examples.htmlkona; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import weblogic.html.*; public class appletexample extends HttpServlet { public synchronized void service(ServletRequest req, ServletResponse res) throws IOException { try { // Housekeeping for Java Server servlets res.setStatus(ServletResponse.SC_OK); res.setContentType("text/html"); res.writeHeaders(); // Construct the AppletElement AppletElement applet = new AppletElement("Blink.class", 300, 100, AlignType.center); applet.setCodeBase("http://www.weblogic.com/classes/") .addElement(new ParamElement("lbl ", "This is the next best thing to sliced bread! " + "Toast, toast, toast, butter, jam, toast, " + "marmite, toast.")) .addElement(new ParamElement("speed", "4")); // Create a Servletpage and set its attributes ServletPage hp = new ServletPage("Blinking Text Applet"); hp.getBodyElement() .setAttribute(BodyElement.bgColor, HtmlColor.white); // Add the AppletElement to the page hp.getBody() .addElement(new HeadingElement("This is the Blinking " + "Text Applet from Sun")) .addElement(applet) .addElement(MarkupElement.HorizontalRule); hp.output(res.getOutputStream()); } catch (Exception e) { defaults.showException(e, res.getOutputStream()); } } }
Different browsers treat embedded objects in different ways. You should understand the behavior of your target browser when using this extension.
Here is a simple Netscape example that displays information from records retrieved from an employee database into the dbKona QueryDataSet "qs". This example uses WebLogic JDBC, a Java-only implementation of JDBC, to connect to an Oracle database through WebLogic. Information for the connections between the WebLogic JDBC client, the WebLogic JDBC Server, and the Oracle database are handled by methods in the defaults class. To run the examples, you need to edit this file and recompile the directory. Here are the methods we use from the defaults class: import netscape.server.applet.HttpApplet; import java.io.*; import java.util.*; import xjava.sql.*; import weblogic.db.xjdbc.*; import weblogic.common.*; import weblogic.html.*; public class defaults { public static Connection login(T3Client t3) throws Exception { // Sets parameters for the connection between // the WebLogic JDBC Server and the DBMS // (the two-tier connection). Properties dbprops = new Properties(); dbprops.put("user", "scott"); dbprops.put("password", "tiger"); dbprops.put("server", defaults.server()); // Sets parameters for the connection between // the T3Client, the WebLogic JDBC Server, and // the DBMS (the multitier connection). Properties t3props = new Properties(); t3props.put("weblogic.t3", t3); t3props.put("weblogic.t3.dbprops",dbprops); // Sets the class name and URL of the two-tier // JDBC driver for the connection between the // WebLogic Server and the DBMS. t3props.put("weblogic.t3.driver","weblogic.jdbc.oci.Driver"); t3props.put("weblogic.t3.url", "jdbc:weblogic:oracle"); // Sets the class name and URL of the multitier // (Java-only) driver for the connection between // the T3Client, WebLogic Server and the DBMS. Class.forName("weblogic.jdbc.t3client.Driver") .newInstance(); Connection conn = DriverManager.getConnection("jdbc:weblogic:t3client", t3props); return conn; } // Specifies the URL for the WebLogic Server that // will be listening for T3Client requests. public static final String t3clienturl() { return (String)System.getProperty("t3url", "t3://localhost:7001"); } // Provides connection information to your database. public static final String server() { return (String)System.getProperty("server", "DEMO"); } // Outputs a stack trace onto an HTML page when // there is an exception. public static void showException(Exception e, OutputStream out) throws IOException { ServletPage hp = new ServletPage("An Exception occurred"); ByteArrayOutputStream ostr = new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(ostr)); hp.getBody() .addElement(new HeadingElement("Exception occurred:", 2)) .addElement(new LiteralElement(ostr.toString())); hp.output(out); } // Sets defaults for htmlKona page generation. public static void setPageDefaults() { TableCaptionElement.defaultAlign= AlignType.top; TableElement.defaultCaption = new TableCaptionElement(""); TableElement.defaultBorder = 4; TableElement.defaultCellspacing = 2; TableElement.defaultCellpadding = 2; TableElement.defaultWidth = "100%"; } }The example uses methods in the defaults class to get information for DBMS connections, page defaults, and to show exceptions. In this example, we use a WebLogic JDBC Client to connect to the DBMS through WebLogic's JDBC Server. WebLogic JDBC requires no client-side libraries, and, consequently, is appropriate for use in applets, although we use it in this example for serverside Java. Because dbKona is a higher-level abstraction that doesn't depend on vendor-specific constructs of data, you can use dbKona to write programs that can retrieve data from any SQL database in a very consistent way. We could adapt this example for use with Sybase or Microsoft SQL Server by doing nothing more than changing the connection information in the defaults class. In this example, we use serverside Java to connect to a database and display information from it. We insert, modify, and delete several records from a database, using dbKona DataSets, which provide automatic generation of SQL and Query-by-example (QBE) functionality. import netscape.server.applet.HttpApplet; import java.io.*; import java.util.*; import weblogic.db.xjdbc.*; import weblogic.html.*; import xjava.sql.*; public class example5 extends HttpApplet { public synchronized void run() throws IOException { T3Client t3 = null; Connection conn = null; try { // Housekeeping for Netscape serverside Java this.returnNormalResponse("text/html"); // Connection is handled by methods in the default class t3 = new T3Client(defaults.t3clienturl()); t3.connect(); defaults.setPageDefaults(); conn = defaults.login(t3); // Create 3 SQL statements Statement stmt = conn.createStatement(); String insert = "insert into emp(empno, ename, job, deptno) " + "values (8000, 'MURPHY', 'SALESMAN', 10)"; String update = "update emp set ename = 'SMITH', " + "job = 'MANAGER' where empno = 8000"; String delete = "delete from emp where empno = 8000"; // Execute the 1st statement and verify results stmt.execute(insert); TableDataSet ds1 = new TableDataSet(conn, "emp"); ds1.where("empno = 8000") .fetchRecords(); // Execute the 2nd statement and verify results stmt.execute(update); TableDataSet ds2 = new TableDataSet(conn, "emp"); ds2.where("empno = 8000") .fetchRecords(); // Execute the 3rd statement and verify results stmt.execute(delete); TableDataSet ds3 = new TableDataSet(conn, "emp"); ds2.where("empno = 8000") .fetchRecords(); // Construct the page and set its attributes ServletPage hp = new ServletPage("Example 5"); hp.getBodyElement() .setAttribute(BodyElement.bgColor, HtmlColor.white); hp.getBody() .addElement(MarkupElement.HorizontalLine) .addElement(new HeadingElement("INSERT results", 2)) .addElement(new HeadingElement("Using SQL:", 3)) .addElement(new LiteralElement(insert)) .addElement(new LiteralElement(ds1)) .addElement(MarkupElement.HorizontalLine) .addElement(new HeadingElement("UPDATE results", 2)) .addElement(new HeadingElement("Using SQL:", 3)) .addElement(new LiteralElement(update)) .addElement(new LiteralElement(ds2)) .addElement(MarkupElement.HorizontalLine) .addElement(new HeadingElement("DELETE results", 2)) .addElement(new HeadingElement("Using SQL:", 3)) .addElement(new LiteralElement(delete)) .addElement(new LiteralElement(ds3)) .addElement(MarkupElement.HorizontalRule) .addElement("Copyright 1996-98, BEA Systems Inc."); hp.output(getOutputStream()); // Close the DataSets ds1.close(); ds2.close(); ds3.close(); } catch (Exception e) { defaults.showException(e, getOutputStream()); } // Close the connections and disconnect finally { try {conn.close();} catch (Exception e) {;} try {t3.disconnect();} catch (Exception e) {;} } } }For more detail on implementing with dbKona, check the Developers Guide, Using dbKona.
WebLogic can execute a Java class file that subclasses javax.servlet.http.HttpServlet (or weblogic.html.FormServlet) as a response to an HTTP request; WebLogic, when a dochome is configured, can serve arbitrary files like HTML pages, images, applets, and archives, and can also proxy requests to to another HTTP server. htmlKona classes are most commonly executed as server-side Java, which we'll discuss here in terms of using htmlKona with WebLogic. This means that you have compiled your htmlKona .java file into a class file which you register in your weblogic.properties file and place in your WebLogic Server host's CLASSPATH. When a user requests that class file (with a URL), the class file is executed and its results are returned as a response to the HTTP request. Writing a class with htmlKona that is destined to be used as server-side Java means that you must structure the class file in a way that is appropriate to the HTTP server that will respond to a request for the class file. WebLogic supports the Java standard servlet API, and htmlKona is optimized for such a use. This means importing the proper classes and writing classes that match the request/response pattern that the HTTP server expects. Standard Java Servlet API exampleHere is a general outline of how you implement for server-side Java using the Java Servlet API. WebLogic serves servlets that conform to this API, specifically subclasses of javax.servlet.http.HttpServlet. All of the forms and interactive pages on WebLogic's website use servlets like these, running on WebLogic. A little history: WebLogic has supported the Java Servlet API since its inception as Jeeves (versions A1.2 and A2). In version 1.0 of the Java Servlet API, JavaSoft changed the servlet package names to begin javax. If you are upgrading your servlets for use with WebLogic version 2.5 or later, you will need to change the package names from java.servlet to javax.servlet. You may also be subclassing FormServlet. Long before we had web servers that supported servlets, htmlKona supported a class called FormServlet. When Jeeves version A2 was released, Jeeves had support for a subclass of HttpServlet called FormServlet, and at that time, WebLogic dropped its own FormServlet to support the Javasoft standard. But version 1.0 of the Servlet API dropped support for FormServlet. So, in order to continue to provide support for those who might have existing classes that use FormServlet functionality, we resurrected FormServlet and reinstated it in the htmlKona API. In release 3.0, FormServlet was deprecated in favor of form-related functionality that was available in HttpServlet. If you aren't using FormServlet already in your classes, there is no need to start. All of the functionality is readily available in the more general HttpServlet. (Specifically you can implement the doGet() and doPost() method to process the query, or you can override the service() method, which dispatches the request to either doGet() or doPost(), depending on the request. The doGet() and doPost() methods are implemented as no-ops in HttpServlet.) For that reason, the FormServlet class has been deprecated, although WebLogic will continue to support it for backwards compatibility.
package examples.htmlkona; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import weblogic.html.*; public class example1 extends HttpServlet { public synchronized void service(HttpServletRequest req, HttpServletResponse res) throws IOException { // Set the status and content type on the response object res.setStatus(HttpServletResponse.SC_OK); res.setContentType("text/html"); // Create a servlet page and add one string to it ServletPage sp = new ServletPage("Example 1"); sp.getBody().addElement("Hello world!"); // Call the page's output method with the response // object's output stream sp.output(res.getOutputStream()); } }
One of the drawbacks of developing programs for serverside Java is that you must restart the server each time you compile a class, since each class is loaded only once (the first time it is requested). When you are testing and tweaking, you may prefer to output your htmlKona class into an HTML file that you can view for testing without a server. You can use the Java compiler to generate the HTML that your code will produce, direct the output into a file, and then view that file in a browser to check layout, colors, etc. (Of course, you cannot test user input within forms without a server.) To output your htmlKona class into a file:
|
|
Copyright © 2000 BEA Systems, Inc. All rights reserved.
|