Using WebLogic JHTML
I. IntroductionNote: For future HTTP servlet projects, we recommend you use JSP instead of the older JHTML standard.
JHTML is a JavaSoft standard for combining Java with HTML pages. In particular, JHTML makes it easy to intersperse dynamic data within your HTML pages. If you understand HTML and you know a little about Java, you can learn how to use JHTML very quickly. If you are just beginning with Java, check out the Java tutorial at the JavaSoft site. WebLogic offers support for the Java specification for JHTML, which is part of the Java WebServer API (Page Compilation technology) recently introduced by JavaSoft. JHTML allows you to embed Java into a standard web page. You -- or your marketing department -- can create a web page in any HTML editor, and then you -- or your engineering team -- can add Java to the HTML page. The WebLogic Server interprets your JHTML and will send a web page to your client's browser. The ability to combine Java with HTML makes it easy to design the layout of your web page using HTML, whilst embedding dynamic data that can be retrieved from a database or derived from user input, using Java. WebLogic's implementation of JHTML is very similar to that used in JavaSoft's WebServer. You can find good documentation for new-comers to HTML and Java at their website on Introducing Page Compilation. This document assumes you have some experience with Java and that you are very familiar with HTML.
To get started with JHTML, you need to add a few properties
to your weblogic.properties
file. Check the section below on Setting up WebLogic.
JHTML is implemented using a special HTML servlet that comes as standard with the WebLogic Server, called the PageCompileServlet. The PageCompileServlet is set up by default to handle all HTTP requests for files ending in ".jhtml". The PageCompileServlet calls upon the JHTML compiler to compile the JHTML file into a standard Java HTTP servlet , and executes the new servlet on the fly. The resulting HTTP servlet delivers a web page in response to the client browser. The JHTML file is only compiled when it is visited for the first time, or when the JHTML file has been changed since it was last compiled. Otherwise, the previously compiled JHTML servlet class is used, making subsequent responses much quicker. It is possible to use the JHTML Compiler stand alone. You can look at the ".java" files it produces, or just register the HTML servlet ".class" files. II. Converting between JHTML and JSPThis guide will help you convert your legacy JHTML pages into JSP format.The first step to convert your JHTML pages by hand is to copy the file to a similarly named file, but using the extension .jsp in place of .jhtml. You will need to open the copied JSP file in a text editor and start making changes by hand. Mapping JHTML syntax to JSPThis table shows the corresponding JSP tags to use in place of JHTML tags in your converted JSP.
Referencing HTTPServlet variablesOne of the biggest obstacles faced when converting from JHTML to JSP are the changes required to cope with the different underlying architectures. Often, JHTML pages may presume that the generated servlet class implementation extends an HTTPServlet, and may reference the inherited methods and member variables of the presumed super-classes. The generated JSP servlets do not extend HTTPServlet, but do provide a number of implicit objects that represent all of the HTTP servlet facilities your JSP page requires. Declaring custom variables with the same names as JSP implicit objects will cause a translation-time error, so you will need to replace such variable names in your JHTML pages with another name. JSP and JHTML share the same implicit object names and types for request and response. You may refer to both as you would in a JHTML page. However, in JSP, there are other ways in which you may set attributes of the response object. The page directive allows you to set the content type of the response and the character set. The <jsp:useBean> tag provides a clean way to add variables to various levels of scope, including the HTTPSession, and the JSP implicit object session represents the HTTPSession in the HTTPResponse. III. Setting up WebLogic for JHTML
Before you can request a .jhtml file, you must set up the WebLogic Server with
the following properties in your
weblogic.properties
file.
The PageCompileServlet is a standard HTTP servlet included with the WebLogic Server. You must register it to handle all HTTP requests for files ending with the suffix ".jhtml" using the line: weblogic.httpd.register.*.jhtml=\ weblogic.servlet.jhtmlc.PageCompileServletYou can add additional registrations to instruct the PageCompileServlet to handle other file suffixes (such as "*.htm", "*.html", and "*.txt") using a similar syntax to that above. The use of an extension takes precedence over any default servlet registration. You set up initialization arguments for the PageCompileServlet using the standard servlet initArgs property as shown here:
Related propertiesThe following are related properties that you may need to set in your weblogic.properties file. These properties are used by other services of the WebLogic Server. When changing their settings you should consider the impact on other services.Setting the Document RootThis is the directory where you publish your ".jhtml" files on the WebLogic Server. You set this using the property:
weblogic.httpd.documentRoot=pathwhere path is an absolute directory path, or a relative directory path from the myserver/ directory under your WebLogic installation. For example, if you set the property to: weblogic.httpd.documentRoot=jhtmlYou would publish your JHTML files in the directory: $WEBLOGICROOT/myserver/public_html/jhtml. If you do not set this property, it will default to the $WEBLOGICROOT/myserver/public_html directory. The document root is the top level directory where the WebLogic Server searches for all published web pages. This property is also used by the FileServlet, which is registered by default to deliver all other types of HTTP media. Setting up session trackingTo enable session tracking, set this property to "true": weblogic.httpd.session.enable=trueOther properties related to session tracking can be found in the "Using WebLogic HTTP Servlets" developer's guide. Other propertiesOther useful related properties include:
IV. Implementing with WebLogic JHTML
JHTML tags supported in WebLogic
Here is a quick reference list of the tags used in WebLogic JHTML. Note that
all of these <java> tags require an
ending </java> tag. All of these tags
can be included inside, or combined with, java comments. For example, the tags:
Note: WebLogic does not currently support the <servlet> tag. Reserved words in JHTMLJHTML reserves the use of these words within embedded Java code. In this case, you use these words as objects in your Java code.
A simple example
Here is a very simple page that mixes HTML with embedded Java. Notice these basics:
<html> <head><title>Hello World Test</title></head> <body> <h1> <font color=#DB1260> Hello World Test </font></h1> <java> out.print("Java-generated Hello World"); </java> <p> This is not Java! <p><i>Middle stuff on page</i> <p> <java> for (int i = 1; i<=5; i++) { out.print("This is a Java loop! " + i + "<p>"); } </java> </body> </html> Here is what the resulting page will look like after it is compiled:
In this section, we describe how the Java in your JHTML page relates to a regular Java class, and how it is compiled into an HTTP servlet. The JTHML compiler turns your JHTML file into an HTTP servlet ".java" file. The resulting file must be a legal ".java" file so it may be compiled by a regular java compiler. In effect, all of your plain HTML is turned into Java write() statements that send the HTML to the HTTPServletResponse output stream. You include Java code in your HTML page by wrapping it in special <java> tags. The order of the HTML print statements and the Java code are preserved, and essentially make up the body of the HTTP servlet's 'service' method. For more details on the structure of an HTTP servlet, see the "Using WebLogic HTTP Servlets" developer's guide. Since your JHTML is ultimately translated into plain Java, you can use any Java constructs, classes or WebLogic services within your JHTML page, just as you would for writing a regular servlet. For more details on using WebLogic services from server-side Java see "Using WebLogic services from an HTTP servlet" in the HTTP servlet developer's Guide. Note: Make sure that the names of your .jhtml files do not collide with any of your other servlet or applet classes. All the .jhtml files are eventually compiled into .class files, and so you should not use any names that conflict with any existing servlet or applet class that may be in your WebLogic Server's CLASSPATH . Other types of tags allow you to define and declare other sections of the generated servlet class from the JHTML file.
In this section, we build upon an example that illustrates a simple database
login, interrogates a database, and displays the results in a web page.
<java type=import> import java.io.*; import java.sql.*; </java> Defining the body of the service methodAs we described above, your JHTML is first compiled into a standard HTTP servlet Java file, then compiled using a standard java compiler. The order of the HTML and the Java in the JHTML page is preserved when translated into Java source code. For instance, you might:
<html><body> <java> for (int i=0; i<10 ; i++) { </java> <h1>Hello World!</h1> <P> <java> } // End of for loop </java></body></html>This will result in "Hello World!" being written 10 times in an HTML page. Declaring class scope objects
You may declare class scope objects such as variables, methods, and
inner classes between the <java
type=class> tags in a JHTML file. You may use any number of this
type of java tags in your JHTML, but we recommend that you group related
variables together at the start of your JHTML for maintainability reasons.
In the following example, we set up some variables that are used by the HTTP
servlet class. We have taken these out of the above <java> tag so that
they may be accessed from other methods, and they are not instantiated on
every call. The new variable declarations now look like this:
Embedding a Java method in a JHTML fileThis example illustrates how to define a class method in your JHTML file that is called from the main <java> block. The short method getCon() initializes a JDBC Connection object that is used elsewhere in the servlet. Note that we wrap the work of the method in a try block so a failure will not break the servlet. <java type=class> static final String jdbcClass = "weblogic.jdbc.oci.Driver"; static final String jdbcURL = "jdbc:weblogic:oracle:goldengate"; static final String user = "scott"; static final String password = "tiger"; protected Connection getCon() { Connection conn = null; try { Class.forName(jdbcClass).newInstance(); conn = DriverManager.getConnection(jdbcURL, user, password); } catch (Exception f) { } return conn; } </java>You can call this method from any other Java code in your JHTML. Notice that the other variables declared in this block are at class scope, so they also can be referenced from any <java> block in your JHTML. Using the backtickBy default, WebLogic supports the use of the backtick in Java tags. You can insert arbitrary backticks anywhere in your HTML. A Java statement within a backtick is evaluated, converted to a string, and sent to the servlet output stream. Backticks are essential for inserting dynamic content within HTML tags, such as a link to another document, based on some variable value. The backtick in WebLogicUnder the Java WebServer, you can embed a Java expression in any arbitrary HTML tag by enclosing it in backticks. We take this functionality one step further in WebLogic JHTML, and backticks are valid inside and outside of java tags. This is very convenient for embedding small pieces of java in your HTML to generate dynamic content since it keeps the HTML in a readable format.Using the backtick in this manner means that you can no longer use a backtick character directly in your HTML code. The workaround is to print a backtick to the output stream within <java> tags. Since the backtick is rarely used, the convenience of using backtick-java-expressions in your HTML far outweighs this drawback.
You can enable and disable the extended use of backticks by setting the
following property in the
weblogic.properties file:
A simple exampleHere is a line from an example we use later in this document:<td>`ds.getString("empno") != null ? ds.getString("empno") : " "`</td>Where ds is a Java class that we have initialized elsewhere in our JHTML file. Here, we use the backtick to insert the result of a Java expression -- the employee number, or a non-breaking-whitespace character -- into an HTML table element. Note that within the Java method out.print, backticks are treated as characters and do not end the Java code. Using session trackingWebLogic's HTTP server also supports session tracking, which allows you to track information about a user as they progress through your web application. For example, an online auction or trading application might use session tracking to keep up with what a user has added to a shopping basket or the bids a user is making on an item for sale. You access a session from the request keyword, with the getSession() method, which returns an HttpSession object. You can add data to or retrieve data from the HttpSession object using arbitrary name=value pairs. The following example illustrates how you would include the contents of a session in the HTML response to a request. <html> <head> <title>Using session tracking</title> <java type=package>tutorial.servlets.jhtml</java> </head> <body bgcolor=#FFFFFF> <h3>Values already in Session:</h3> <table border=1 width="100%"> <java> HttpSession session = request.getSession(true); String[] valueNames = session.getValueNames(); for (int i = 0; i < valueNames.length; i++) { String name = valueNames[i]; String value = session.getValue(name).toString(); out.print("<tr><td>" + name + "</td><td>" + value + "</td></tr>"); } </java> </table> You add data to a session in a similar way, but using the putValue() method. This example retrieves all parameter name=value pairs from the query data of the request and stores them in a session. <h3>Values to add to Session:</h3> <table border=1 width="100%"> <java> Enumeration paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String name = (String)paramNames.nextElement(); String[] values = request.getParameterValues(name); session.putValue(name, (values!=null ? values[0] : "null")); out.print("<tr><td>" + name + "</td><td>" + value + "</td></tr>"); } </java> </table> </body> </html> Note that to use session tracking with WebLogic, you will need to add a property to the weblogic.properties file for WebLogic. There is more information on using session tracking and cookies in the Developers Guide Using WebLogic HTTP Servlets. This example demonstrates how you should access a database from JHTML to include dynamic content in your web pages. <java> try { String jdbcClass = "weblogic.jdbc.oci.Driver"; String jdbcURL = "jdbc:weblogic:oracle:goldengate"; String user = "scott"; String password = ""; password = "tiger"; Class.forName(jdbcClass).newInstance(); Connection conn = DriverManager.getConnection(jdbcURL, user, password); out.print("<p>First " + "login attempt was successful for "); out.print(user + "/" + password); password = "tigger"; Class.forName(jdbcClass).newInstance(); Connection conn2 = DriverManager.getConnection(jdbcURL, user, password); out.print("<p>Second login attempt " + "was successful for "); out.print(user + "/" + password); } catch (Exception f) { out.print("<p>Login failed for " + user + "/" + password); out.print(">p>"); f.printStackTrace(new PrintStream(out)); } finally { try {conn.close();} catch (Exception g) {} try {conn2.close();} catch (Exception h) {} } </java> Let's look at the interesting parts of this example.
IV. Using the WebLogic JHTML compilerSince the PageCompileServlet automatically calls the WebLogic JHTML compiler as required, you generally do not need to directly access it. However, there may be situations (such as debugging) where accessing the compiler directly can be useful. This section is provided as reference for the compiler. The WebLogic JHTML compiler parses the .jhtml file that you produce into a Java file and then compiles the Java file into a class file, all in a single step.
SyntaxThe JHTML compiler works in much the same way that other WebLogic compilers work (including the RMI and EJB compilers). Here is the pattern: $ java weblogic.jhtmlc -options fileNamewhere fileName is the name of the .jhtml file that you want to compile. The options may be before or after the target filename. Here is an example that compiles "myFile" into the destination directory (one of the options) "weblogic/classes". $ java weblogic.jhtmlc -d /weblogic/classes-jdk110 \ myFile.jhtml ArgumentsThe options available are:
V. Change history
|
|
Copyright © 2000 BEA Systems, Inc. All rights reserved.
|