HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

With all the hype and press concerning Servlets lately, it seems as though this Java technology is ready to replace CGI as the preferred way to perform server-side processing on Web servers. Unfortunately for Servlets, just being better than CGI at server-side processing is no longer enough to be the de facto standard. Last year, a whole new approach to dynamic Web development turned CGI on its head. This new technology was called Active Server Pages, brought to us by our friends in Redmond. Offering true Rapid Application Development and a choice of scripting languages to use, Active Server Pages quickly dethroned CGI on IIS Servers and made developers much more productive. Recognizing this fact, Sun Microsystems has offered a new version of its Java Web Server that supports the dynamic compilation of Web pages mixed with Java code. Their current offering uses Web pages with a JHTML extension, which are compiled on the fly into Servlets. At JavaOne this year, Sun and third-party Servlet Engine providers, such as IBM and Live Software, demonstrated JavaServer Page technology as an evolutionary step from JHTML. JavaServer Pages have been made to look just like Microsoft's Active Server Pages in an attempt to lure their Web developers into the Java fold. It's a great idea that marries the productivity of rapid Web development to the most powerful language in the world...Java. JavaServer Pages are in beta right now and are not suitable for production use; therefore this article will focus on the use of JHTML on the Java Web Server. JHTML pages will enable you to be just as productive as you would using either ASP's or JSP's, the only difference being the special tags that are defined within each.

Because a Java development tool is not required, the Java Web Server and your favorite HTML editor are all you'll need to get started. If you don't own the Java Web Server, you can download a 30-day trial version at http://java.sun.com/javastore/jserv/buy_try.html. To begin, create a basic Web page in the public_html directory of the Java Web Server and save it with the extension .jhtml. You will not be able to view this JHTML page by double-clicking on it; you must first open your browser and then type in the proper URL to view it. You'll notice that whenever you make changes to your JHTML page that it will take about five seconds for it to open in your Web browser. This is because the Java Web Server compiles your JHTML page into a Servlet every time you make a change to it. The good thing to know is that unlike Active Server Pages that are interpreted every time they're requested, your JHTML-created Servlet is compiled and then stays resident in memory for fast execution.

The first topic covered in this article is the new Java Tags that you'll mix in with your HTML Tags. The most commonly used tag is the <java> tag. This tag tells the Java Web Server that it will find Java code to compile in between <java> and </java>. If you want to insert Java code inside the structure of an HTML tag, you will put your code between two ticks ` ` instead of two <java> tags. To print the value of your Java code, you would insert that code inside the <java type="print"> </java> tags. To import Java classes into your Web page, you will first use the <java type="import"> tag followed by the classes you wish to import. A number of other Java tags are available, but the ones I've just covered are the only ones we'll need to proceed.

There are a few things that I recommend you put at the top of your JHTML pages to ensure that you never have any problems utilizing all the features that the Servlet API provides. For starters, add the code in Listing 1 to the top of your page. Then add the code in Listing 2 to see an example of using a Java loop to dynamically build a table so that you can get a feel for how your code should look in the context of a Web page.

The next topic we'll discuss is the use of cookies. JHTML pages can send and receive cookies to a user's browser to store information. The code in Listing 3 demonstrates their use. You've probably noticed the use of the code "out.print();" in Listing 3. This code is used to send data back to the browser from inside two <java> </java> tags.

Cookies are often utilized to track sessions or maintain state. An easier way to do this is to use the Session Tracking feature that is built into the Java Web Server. Session variables use either cookies or URL rewriting to store your Java variables throughout the lifetime of a particular session with a particular user. Using Session variables eliminates the need for the manual use of cookies to maintain variables and state. To use Session variables on a particular page, you must first include this line of code:

<java>
HttpSession session = request.getSession(true);
</java>

With this code added, you can add, retrieve and remove Session variables using the code shown in Listing 4.

Another way that data is maintained between Web pages or sent to the server is through the use of form submissions and QueryStrings. With JHTML pages, you can receive data that is sent from another page using the getParameter() method. Listing 5 shows the code to retrieve submitted data.

Many times you may find yourself submitting data to another JHTML page whose sole purpose is to take that data and insert it into a database. Usually, after doing such a database operation, you will want to redirect the user to another Web page. This is accomplished using the sendRedirect() method. An important thing to remember is that you can use it only before you send any data back to the Web browser; once you've sent out any kind of data, the sendRedirect method will fail. Below is the code required to redirect a Web page:

<java>request.sendRedirect("index.html")</java>

An important thing to note when using this feature is that the closing </java> tag sends out a CRLF to the browser, which is enough to make your redirect code fail. Listing 6 is an example of code that will fail. Listing 7 shows you how to make the redirect code work when you have </java> tags above it.

The next thing to discuss is how to reference core and third-party classes from a JHTML page. Accessing core Java classes from your JHTML page is straightforward and requires no special settings. You've already seen the code to import core classes in Listing 1. Accessing third-party classes, as well as classes you've built yourself, is a little tricky and requires a few extra steps. The first thing you must do is create a "classes" directory off your Java Web Server directory: C:\JavaWebServer1.1\classes. A CLASSPATH is not required, since the Java Web Server picks up the "classes" directory on startup. Subdirectories of your "classes" directory will mirror your different Java Packages. The Java Web Server requires that all of your classes be inside a package. The SendMail class that will be used in the next example references a package called smtp. A proper directory path enabling this class to work would be C:\JavaWebServer1.1\classes\smtp\SendMail.class. To reference this class in your JHTML file, you must first import it at the top of your page just as you do with core classes. In the case of the SendMail class residing in the smtp package, your code will look like Listing 8.

Finally, because nearly everyone uses databases with their Web pages, Listing 9 illustrates an example of JHTML database access. This article should provide you with enough information to get started on your own with JHTML.

About the Author
Robert Tiffany is a senior technology consultant with Insource Technology in Houston, TX. He is currently working on an e-commerce Website using servlet technology for the George Bush Presidential Library. Robert has worked on a lot of Internet/intranet/extranet development with both Active Server Pages and Enterprise Java technologies. Past employers have included Boeing, Microsoft and Real Time Data. You can reach Robert at [email protected]

	

Listing 1.

<java type=import>
java.io.*
javax.servlet.*
javax.servlet.http.*
</java>

Listing 2.

<java type=import>
java.io.*
javax.servlet.*
javax.servlet.http.*
</java>

<html>
<head>
<title>Java Loop</title>
</head>
<body>

<table>
<java> for (int I = 0; I < 5; I++) { </java>
	<tr>
		<td>
			<java type=print> ²<b>² + I + ³</b>² </java>
		</td>
	</tr>
<java> } </java>
</table>

</body>
</html>

Listing 3.

<java type=import>
java.io.*
javax.servlet.*
javax.servlet.http.*
</java>

<html>
<head>
<title>Java Cookies</title>
</head>
<body>

<java>
//sending cookies
Cookie outCookie = new Cookie(³Name², ³Value²);
outCookie.setMaxAge(2 * 24 * 60 * 60);
response.addCookie(outCookie);

//receiving cookies
Cookie inCookie[] = request.getCookies();
for (int I = 0; I < inCookie.length; I++) {
	out.print(inCookie[I].getName());
	out.print(inCookie[I].getValue());
}
</java>

</body>
</html>

Listing 4.

<java>
session.putValue("Item", "Shirt");  //adds an Item called Shirt
session.getValue("Item") //gets the Item and returns Shirt
session.invalidate //kills this session
if (session.isNew()) {	//checks to see if you're new 
	...do this...;
}
</java>

Listing 5.

<java>
String x = request.getParameter(³Name²);
out.print(x);
</java>

Listing 6.

<java type=import>
java.io.*
java.net.*
</java>

<java>request.sendRedirect("index.html")</java>

Listing 7.

<java type=import>
java.io.*
java.net.*
</java><java>request.sendRedirect("index.html")</java>
	

Listing 8.

<java type=import>
smtp.SendMail
</java>

<html>
<head>
<title>Send some mail</title>
</head>
<body>

<java>
SendMail x = new SendMail();
x.smtpHost = "mx2.insource.com";
x.smtpFrom = "[email protected];
x.smtpToEmail = "[email protected];
x.smtpToName = "Brian Towles";
x.smtpSubject = "The Java Web Server can send email";
x.smtpMessage = "Hello World";
String result = x.Send();
out.print(result);
</java>

</body>
</html>

Listing 9.

<java type=import>
java.sql.*
</java>
		
<html>
<head>
<title>dbselect</title>
</head>
<body>

<java>
try {
	//load oracle driver
	DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
	//connect to database
Connection cn = DriverManager.getConnection
(³jdbc:oracle:thin:@host:1521:orcl², ³scott², ³tiger²);

	//query
	Statement st = cn.createStatement();
	ResultSet rs = st.executeQuery(³select ename from emp²);
</java>

<table>
<java> while (rs.next()) { </java>
	<tr>
		<td>
			<java type=print>rs.getString(1)</java>
		</td>
	</tr>
<java> } </java>
</table>
<java>
rs.close();
st.close();
cn.close();
} catch(Exception e){	out.print(e.getMessage());}
</java>
</body>
</html>
  
      
 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.