- Web Services Architecture
- Java Building Blocks
- The Future of Java Web Services
- Summary
Java Building Blocks
The one constant in developing Web service applications is the requirement for a server application that either implements, wraps, or exposes the desired service. Java provides an excellent framework for building server applications, as evidenced by the JigSaw, Jetty, and Tomcat servers, all Java, all free.
Downloading and Installing Tomcat
To demonstrate using Java to build Web services, we will use the Tomcat server, which provides the reference implementation for the servlet and JSP specifications. Tomcat is developed by Jakarta, a project of the Apache Software Foundation. The main page for the Jakarta project (http://jakarta.apache.org) contains information on a variety of popular open source Java tools, including Tomcat, Junit, and Ant.
The Tomcat server is the official reference implementation for the JSP and Servlet specifications. This is important for two reasons. First, there are multiple version of Tomcat, applicable to different specifications, so you need to be careful when downloading to ensure that you get the correct version. Second, if a Web application works on Tomcat, it must work on any other server that is compliant with the specification (otherwise the other server wouldn't be compliant).
The Tomcat developers have assembled on the Web site a large amount of well written information that describes the server, its installation, as well as instructions for developing and deploying applications that use Tomcat. In this book, we use version 4 of Tomcat.
To simplify installation, you'll probably want to download a binary version of the Tomcat server. If you click on the Binaries link under Download on the Tomcat home page, you are taken to the main Jakarta binary download page, shown in Figure 4.5. From here you need to scroll down until you find the latest release build of the version 4 Tomcat server. Because Tomcat is an open source project, you have access to any version of the server, including development milestones as well as nightly builds. Unless you are very adventurous, you should stick to only the release builds.
Figure 4.5 The primary Jakarta download Web site.
Following this link takes you to the Tomcat release build download page, shown in Figure 4.6. This Web site allows you to access the source package for the Tomcat server, RPM packages to install Tomcat on a Linux system, as well as binary packages. The rest of the Web page contains useful information regarding the Tomcat package.
Figure 4.6 The primary Tomcat download Web site.
If you are working on Linux, follow the RPMS link and download and install the server appropriately. To actually access the software for Windows, however, you should click on the BIN folder, which takes you to the binary download directory shown in Figure 4.7.
Figure 4.7 The Tomcat binary package download Web site.
From here, you can download either a Windows executable that eases installation, or a Zip package containing the Tomcat server. If you already have Java installed, the executable approach is the easiest, because it installs everything and adds Start and Stop icons to your desktop. Alternatively, you can download the Zip file and install the server by unzipping the package into an appropriate directory. If you follow this approach, you will end up with a Tomcat directory hierarchy, as shown in Figure 4.8.
Figure 4.8 The directory structure for the Tomcat installation.
Becoming Familiar with Tomcat
At this point, you have successfully installed the Tomcat server. Before you jump into the next section, however, a brief overview of working with Tomcat is in order. First, the start and stop scripts (either shell script or batch files) are in the bin subdirectory. Configuration information, which you won't need to worry about, is located in the conf directory. To simplify deployment, you drop new Web applications into the webapps folder, and include a customized deployment descriptor, called web.xml. Finally, before JSP pages can be served to a client, they need to be compiled, which the Tomcat server does for you automatically. The intermediate files are generated in the work directory.
To start the Tomcat server, you need to run the startup script, located in the bin directory. After the server is running, open a Web browser and surf to http://localhost:8080/. If you see the welcome screen shown in Figure 4.9, you are in business. Otherwise, retrace your steps, and make sure you have an appropriate JDK installed on your system.
Figure 4.9 The Tomcat welcome page, showing that you have successfully installed and started the Tomcat server.
The Tomcat server comes with several JSP and servlet examples. If you follow the example links from the Tomcat welcome page, you can either test these examples out or see the example source code. Feel free to play with these examples; the actual source code is located in the examples subdirectory of the webapps folder. If you change a servlet after recompiling the Java file, you need to stop and restart the server so that the new classes are reloaded. You know all about starting the server; stopping it is just as easy. The shutdown script, also in the bin directory, shuts the server down properly and releases any acquired resources.
NOTE
When you run a server on a continuously live Internet connectionsuch as a cable modem or DSL connectionyou are possibly opening yourself up to being attacked, especially if you are not behind a firewall. Unless you have taken proper security measures, don't leave a server, such as Tomcat, running for long periods of time unattended. Tomcat provides Web service functionality, so anyone with an Internet connection can connect to your server.
Building Services
After you have the Tomcat server installed, you can start to look at the Java technologies that enable Web services. This section first briefly mentions the Enterprise APIs that are relevant to building Web services, before focusing on both JavaServer pages and servlets.
If we focus on interfacing legacy applications, several Java technologies come to the forefront. First, if you need to connect to a database, Java provides several APIs. First is JDBC, which enables you to connect to a database, execute SQL, and process the results. If you need to utilize only static SQL statements, you should also look at SQLJ, which is an ANSI standard for embedding SQL into Java applications. A relative newcomer to this arena is the Java Data Objects (JDO) API. JDO supports what is known as transparent persistence. This enables a developer to work with Java objects, be they persistent or transient, in exactly the same manner, without worrying about persisting the Java objects and dealing with all the related complications.
If you need to integrate with an existing legacy application, you should investigate the Java Connector Architecture (JCA), Java Messaging Service (JMS), and Enterprise JavaBeans (EJB). JCA provides a standard interface to connect to legacy applications, hiding many of the difficulties in doing so, and thereby increasing productivity. JMS also is useful in this regard, but focuses more on the integration of messaging services. Finally, to minimize the interaction between your Java code and the legacy application, you can use EJBs to cache results.
Two other major concerns that you might have when developing Web services are security and internationalization. In both of these arenas, Java excels. First, Java is inherently safer than most other programming languages when you write secure applications. In addition, Java provides support for Secure Socket Layers (SSLs) with Java Secure Sockets Extension (JSSE), cryptographic communications with Java Cryptography Extension (JCE), as well as authentication and authorization with Java Authentication and Authorization Service (JAAS). And finally, Java itself is Unicode-compliant, and also provides a great deal of support for writing International applications.
Using JavaServer Pages and Servlets
Although all this is impressive, the two most important technologies for building and using Web services are JavaServer Pages (JSP) and servlets. Together with JavaBeans, which simplify the sharing of data among different server components, these two technologies enable developers to build powerful Web applications.
For example, consider the following demonstration of a login form, presented in different languages, depending on the Accept-Language HTTP header in the client request. Listing 4.1 provides an example of a simple JSP page that displays the login form, demonstrating how easy it is to use JSP technology to develop Web applications.
Listing 4.1LogOn.jsp
<%@ page contentType="text/html" import="java.util.*" %> <html> <head> <title> International JSP Login Page</title> </head> <body> <% Locale userLocale = request.getLocale() ; ResourceBundle loginBundle = ResourceBundle.getBundle("LogOn", userLocale) ; %> <h1> <%= loginBundle.getString("welcome") %> </h1> <hr/> <h2> <%= loginBundle.getString("message") %> </h2> <form> <input type="text" name="user"/> <%= loginBundle.getString("user") %> <p/> <input type="text" name="pass"/> <%= loginBundle.getString("passwd") %> <p/> </form> </body> </html>
If you are familiar with JSP pages, you might notice that Template date was not used for the textfield labels. Instead, the labels are obtained from a ResourceBundle, which is selected at request-time via a Locale object, which is determined from the HTTP Accept-Language header. For this example to work, it's necessary to create Property files that define the necessary Strings for the different Locales that are to be supported. The first one is the LogOn_en_US.properties file, shown in Listing 4.2, which contains the Strings that normally would have just been placed into the JSP file as template data. After that, two more property files have the translated strings in Spanish (Listing 4.3), and German (Listing 4.4). Note that these were not translated professionally as would be done in a production environment.
Listing 4.2LogOn_en_US.properties
passwd=Password user=Username message=Please Login welcome=Welcome
Listing 4.3LogOn_es_MX.properties
passwd=Palabra de paso user=Username message=Por favor conexi\u00F3n welcome=Recepci\u00F3n
Listing 4.4LogOn_de.properties
passwd=Kennwort user=Username message=Bitte LOGON welcome=Willkommen
To demonstrate this example, Figure 4.10 shows the result of viewing LogOn.jsp in Internet Explorer 6.0.
Figure 4.10 The LogOn JSP page shown for the U.S. locale.
Most browsers enable the user to change locales easily. For example, to change locales in Internet Explorer, open the Internet Options dialog, which is available from the Tools menu. The Internet Options window, shown in Figure 4.11, enables you to customize the behavior of the browser.
Figure 4.11 The Internet Options window, where a user can customize the behavior of the browser.
Near the bottom of the main panel is a Languages button. If you click this button, a new dialog opens, which enables you to set your language preferences. If you click Add, you are shown the window in Figure 4.12, which lists all the languages that IE supports.
Figure 4.12 Languages supported by IE.
To test the LogOn.jsp page, follow these steps:
Select German (Germany) [de] from the list of languages and click OK.
Select the order of the languages. Click on German, and use the Move Up button to move it ahead of any other languages that are listed.
Click on OK to close the Add Language dialog, and also click on OK to close Internet Options.
If you reload the LogOn.jsp page, your Login form is now displayed in German, as shown in Figure 4.13.
Figure 4.13 The LogOn.jsp page showing the Login form in German.
If you repeat the previous process, but this time select Spanish (Mexican) [es_mx] from the list of languages, and move it to the top of the Preferred Languages, your browser now requests content with the Mexican Spanish locale. This time, LogOn.jsp displays the Login form in Spanish.
Two exciting new features have recently been added to the JSP and Servlets specification: custom actions and filters. They're discussed next.
Custom Actions
With JavaServer Pages, developers can now create and utilize custom actions, which are implemented as new tags in a JSP page. Custom tags enable JSP developers to remove Java code from JSP pages, which enables non-Java developers to generate dynamic JSP Web applications. Organizations such as Jakarta have also created custom tag libraries that enable a JSP developer to quickly add new functionality to a Web application with minimal coding. For example, Jakarta has a custom tag library that simplifies developing Internationalized JSP applications. Listing 4.5 shows how LogOn.jsp could be written using this tag library.
Listing 4.5tagLogOn.jsp
<%@ taglib prefix="logon" uri="http://java.sun.com/jstl/ea/fmt" %> <html> <head> <title> International JSP Login Page</title> </head> <body> <logon:locale value="<%= request.getLocale() %>"/> <logon:bundle basename="org.apache.taglibs.standard.examples.i18n.Resources"> <h1> <logon:message key="welcome"/> </h1> <hr/> <h2> <logon:message key="message"/> </h2> <form> <input type="text" name="user"/> <logon:message key="user"/> <p/> <input type="text" name="pass"/> <logon:message key="passwd"/> <p/> </form> </logon:bundle> </body> </html>
As you can see, this JSP page is almost completely free of Java code. The only remaining Java is in the setting of the locale for the i18n library.
Filters
The new concept of servlet filters enables you to preprocess client requests and to post-process server responses. As a simple example, consider the filter in Listing 4.6, which, when properly deployed, intercepts client requests and blocks any request that has a U.S. locale; see Figure 4.14.
Listing 4.6LocaleFilter.java
package com.sams ; import java.util.* ; import javax.servlet.*; import javax.servlet.http.*; public class LocaleFilter implements Filter { private ServletContext ctx ; private final static String msg = "English U.S. locale is currently blocked" ; public void init(FilterConfig config) throws ServletException { ctx = config.getServletContext() ; ctx.log("Initializing Locale Filter") ; } public void destroy() { ctx.log("Destroying Locale Filter") ; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, java.io.IOException { HttpServletRequest req = (HttpServletRequest)request ; if(req.getLocale().equals(Locale.US)){ HttpServletResponse res = (HttpServletResponse)response ; res.sendError(res.SC_SERVICE_UNAVAILABLE, msg) ; } } }
Figure 4.14 The effect of the LocaleFilter on blocking those requests that have the Accept-Language HTTP header set to the U.S. locale.
This capability to intercept requests and responses lends itself to many difficult tasks, including simplifying authentication, compressing content, or customizing responses.
User Interfaces
The actual Web service is only half the story, however; the other half is the client that accesses the Web service. Once again, Java is more than up to the task. Java supports the full range of potential clients, from Web browsers, which might actually be written in Java and that support the Java plug-in and now Java Web Start, to devices that utilize J2ME or PersonalJava, to smart cards. If a client exists, Java can probably run on it.
In fact, you can write Web clients in Java that perform double duty. For example, the application in Listing 4.7 can be executed as either a standalone application or as an applet. This simple application could be connected to a Web service, rather than a Web site, so that dynamic selection of contacts is supported. Executing this Java code as an application, shown in Figure 4.15, generates a GUI that displays a picture and enables the user to hear an audio recording.
Listing 4.7LoveZone.java
import javax.swing.*; import java.applet.*; import java.awt.*; import java.awt.event.*; import java.net.URL; import java.net.MalformedURLException ; public class LoveZone extends JApplet { private String soundFile = "hello.wav" ; private String imageFile = "rjb.jpg" ; private boolean inAnApplet = true; private JButton playButton ; private JButton stopButton; private JLabel label ; private JLabel lPhoto ; private AudioClip audioClip ; private ImageIcon icon ; public LoveZone() { this(true); } public LoveZone(boolean inAnApplet) { this.inAnApplet = inAnApplet; try{ audioClip = newAudioClip(new URL("http://localhost:8080/jws/hello.wav")) ; icon = new ImageIcon(new URL("http://localhost:8080/jws/rjb.jpg")) ; }catch(MalformedURLException ex) { System.exit(0) ; } } public void init() { if(audioClip == null) audioClip = getAudioClip(getCodeBase(), soundFile); try{ icon = new ImageIcon(new URL(getCodeBase(), imageFile)) ; }catch(MalformedURLException ex) { System.exit(0) ; } setContentPane(makeContentPane()); } public Container makeContentPane() { label = new JLabel("Greetings from the LoveZone", JLabel.CENTER); playButton = new JButton("Play"); playButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { audioClip.play() ; playButton.setEnabled(false); stopButton.setEnabled(true); return; } }) ; stopButton = new JButton("Stop"); stopButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { audioClip.stop(); playButton.setEnabled(true); stopButton.setEnabled(false); return; } }) ; stopButton.setEnabled(false); lPhoto = new JLabel("", icon, JLabel.CENTER) ; lPhoto.setToolTipText("Hi, I'm Robert") ; lPhoto.setPreferredSize(new Dimension(220, 300)) ; JPanel controlPanel = new JPanel(); controlPanel.setLayout(new BorderLayout()); controlPanel.add(label, BorderLayout.SOUTH) ; controlPanel.add(playButton, BorderLayout.WEST); controlPanel.add(stopButton, BorderLayout.EAST); controlPanel.add(lPhoto, BorderLayout.NORTH) ; controlPanel.setBackground(new Color(255,255,204)); controlPanel.setBorder(BorderFactory.createMatteBorder(1,1,2,2,Color.black)); return(controlPanel) ; } public static void main(String[] args){ try{ UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel") ; }catch(Exception e){ System.err.println("\nERROR When Setting the Metal Look and Feel: "); System.err.println(e.getMessage()); } Frame frame = new Frame("Love Zone Example") ; frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); LoveZone applet = new LoveZone(false); frame.add(applet.makeContentPane()); frame.pack(); frame.setVisible(true); } }
Figure 4.15 The LoveZone application, showing how easy it is to combine images and audio for display in a Java application.
Java Tools
Although the Java programming language itself is starting to mature, native support for Web services within the Java language is only starting to emerge. This doesn't mean you can't implement Web services in Java; there are numerous different Java implementations for the different Web service standards. Eventually, the best attributes from these different efforts will be utilized to provide full native support for Web services in Java. Right now, however, you have to choose from the available commercial and open source products that are available.
Toolkits
For example, the Apache Software Foundation has developed the SOAP toolkit in Java, after an early code donation from IBM. Currently, a completely rewritten version, called AXIS, is available, which extends the communication to more protocols. Both these toolkits are discussed in more detail in Chapter 5, "A Simple Java Web Service."
Other toolkits are available for interacting with UDDI registries, including UDDI4J. Apache AXIS provides support for generating and interacting with WSDL documents. Likewise, a toolkit called WSDL4J also enables developers to work with WSDL documents.
Development Editors
With the maturation of the Java language, multiple vendors have developed powerful development editors that simplify the creation of Java applications, including Java Web services. This also helps the developer, because automatic generation of code and deployment information can improve productivity and shorten development cycles.
One example is the Forte for Java IDE, which comes in two versions. The first version is called the Community Edition, shown in Figure 4.16, and is free to use. The second version is the Enterprise Edition, and can be licensed from Sun. Both versions are based on the open source NetBeans project, available at http://www.netbeans.org.
Figure 4.16 The Forte for Java Community Edition, showing the free Web Application Services Platform (WASP) plug-in from Systinet that provides support for Web services.
IBM is another big player in the Java Web service development arena, having led the initial development of Java-based toolkits for working with SOAP, WSDL, and UDDI. IBM has developed a Web services toolkit, as well as a development editor, shown in Figure 4.17. IBM has donated a large quantity of IDE code to the eclipse project, available at http://www.eclipse.org.
Figure 4.17 The Web Services Studio Development Editor from IBM, which can provide full Web service development, including SOAP, WSDL, and UDDI.
A surprise entrant is JDeveloper from Oracle, which is an enterprise Java development environment, written in Java. JDeveloper, shown in Figure 4.18, provides built-in support for Enterprise applications with Orcale9i application server. Further support for developing Web services is included as well.
Figure 4.18 The JDeveloper IDE, which can be freely downloaded from the Oracle Technet Web site.