1111//3300//22001100 JJaavvaa TTeecchhnnoollooggiieess ffoorr WWeebb AApppplliiccaattiioonnss

http://java.sun.com/developer/technicalArticles/tools/w ebapps_1/ Nov3 0,2 010

Article Technologies for Web Applications

By Dana Nourie, November 2006

YYouou can find wwebeb applications eveveryerywherewhere on the IntInternet.ernet. ManyMany of tthesehese web applicationsapplications are usedused to process online forms ,, tally vvotingoting pollspolls,, taktakee orders within online stores, allow users to book a flight for theirtheir next busibusinessness trip, or simplysimply to display the user's lloginogin namname.e. Which JavJavaa technologies do youyou need to creatcreatee a web application and which packagespackages do you need to import? The answer depends on what kind of applicationapplication yyou'reou're building and whatwhat it does.

This article provides an overview of the Java technologies involved in creating various types of web applications, tells you when you might decide to ususee them, and provides linkslinks to get yyouou sstarttarted.ed. FutFutureure articles will covcoverer how to useuse these technologies in buibuildinglding web applications.applications. To use the technologies describeddescribed in thithiss article, download JavJavaa Development Kit (JDK) 5.0 Update 9 with Java Platform, Enterprise Edition (Java EE) or later and install it on your computer.

BeforBeforee you begin coding, you need to understand whatwhat a webweb application is,is, what JavaJava technologies are availableavailable for use, and what devdevelopmelopmentent toolstools can save youyou time and make creating applications easeasier.ier.

Contents

What Is a Web Application? JavJavaa Technologies to Use in Web ApplicationsApplications OtOtherher Technologies to Consider Consider DevDevelopmelopmentent Tools

What Is a Web Application?

Web applications are by naturnaturee disdistributtributeded applications, meaningmeaning that they are programs that runrun on m ore than one computer and comcommunmunicateicate throughthrough a network or seservrver.er. SpecSpecificallyifically,, web applications are accessaccesseded with a webweb browser er brows and are popular bebecausecause of the easeease of usiusingng the browsebrowserr as a useruser client. ForFor the enterprise,enterprise, the ability toto update and maimaintainntain web applications wiwithoutthout deployingdeploying and ins talling software on potentiallypotentially thousanthousandsds of client computers is a key reason for their popularitpopularityy.. WebWeb applications are ususeded for web mail, online retailretail sales,sales , discussdiscussionion boards,boards, weblogs, online banking, and more. OOnene web application can be accessedaccessed and us ed by mimillionsllions of people.

Like desktop applications, web applications are mmadadee up of many parts and oftenoften contain miniprograms,miniprograms, somesome of which havhavee ususerer interfinterfaces,aces, and somes ome of which do not require a graphical us er interfaceinterface (GUI)(GUI) at all. In addition, web applications frequentfrequently requirerly equire an additional mmarkuparkup or scriptscriptinging lanlanguage,guage, such as HTML,HTML, CSS, or JavaScriptJavaScript proprogrammgramming language..language A Alslso,o, many applications ususee only tthehe JavJavaa programmimingprogram ng language,language, which is ideal becausbecausee of its versversatility.atility.

A A web appapplicationlication can be as ssimimpleple as a page that showsshows the current date and time or as complexcomplex as a ssetet of pages onon which you can look up and book the most convenient flight, hotels, and car rentals for your next vacation.

The Java technologies you'll use to create web applications are a part of the Java EE platform, in addition to many of the JavJavaa Platform, StandardStandard Edition (Jav(Javaa SE) class es and packages. In order for mmanyany of tthesehese technologies to workwork on a serverserver,, the server musmustt havhavee a container, or web server, installed that recognizrecognizeses and runs the classes yyouou create. FFor or devdevelopmelopmentent and testing of these technologies,technologies youy, ou can uuss e the tools detailed inin this article,article, but when yyouou deploy, make sure that the server has Java server software installed to run Java technology-based web applications. If you don't have access to this information, ask the serverserver admiadministrator.nistrator.

Java TecTechnohnologilogieses to Use in WebWeb ApplApplicationsications

There are too many JavJavaa technologies to list in one article, so this article will describe only the ones m ost frequently used. The number of technologies lis ted here can appear overwhelmioverwhelming.ng. Keep in mind that youyou will not need to ususee them all. In

aavvaa..ssuunn..ccoomm//jjsspp__uuttiillss//PPrriinnttPPaaggee..jjsspp??uurr…… 11//77

1111//3300//22001100 JJaavvaa TTeecchhnnoollooggiieess ffoorr WWeebb AApppplliiccaattiioonnss fact, a web application often consists of nothing more than one page created with the JavaServer Pages (JSP) technology. SometimSometimeses you will comcombinebine three or more ssuchuch technologies. No mattatterm er how mmanyany yyouou end up using,us ing, it'sit's good to know what is avavailableailable to you and how you can use each oneone in a web application.

Java Servlet API

The Java Servlet API lets you define HTTP-specific classes. A servlet class extends the capabilities of servers that host applications that are accessed by way of a request-responserequest-response programmingprogramming model.model. AlthoughAlthough servletsservlets can respondrespond to any tytypepe of requesrequest, tt, theyhey areare comcommmonlyonly used to extextendend the applicationsapplications hostedhos ted by web servers.servers. For instance,instance, yyouou mightmight use aa servlet to get the text input from an online form and print it back to the screen in an HTML page and format, or you might use a different servservletlet to write the data to a file or databasedatabase instead.ins tead. A servlet runs on the s erververer sideside -- without an applicationapplication GUI or HTMHTMLL ususerer interfaceinterface (UI) of its owown.n. JavJavaa ServletServlet exextensionstensions mamakeke manymany web applications pos sisible.ble.

Figure 1 sshowshows clients talking to Java ServletServlet exextensionstensions.. Clients m ay rrangeange in complexitycomplexit fy fromrom simplesim ple HTML forformsms toto sophissophisticatticateded Java tectechnology-hnology-basedbased applets.

Figure 1: Servlet Model

The javax.servlet and javax.servlet.http packages provideprovide the classesclasses and interfacinterfaceses to define servrvlets.se lets. HTMLLHTM servlet classes exextendtend the javax.servlet.http.HttpServlet abstract class, which provides a framework for handling HTTP protocol.

Learn more about Java Servlet extensions and navigating with servlets.

JavaServer Pages Technology

JavaServer Pages (JSP) technology provides a simplified, fast way to create dynamic web content. JSP technology enables rapid development of weweb-basedb-based applications that are server- and platform-independent.platform-independent. JSP techtechnologynology lets you add snippets of servlet code directly into a text-based document. Typically, a JSP page is a text-based document that contains two types of text:

Static data, which can be expressed in any text-based format, such as HTML, Wireless Markup Language (WML), or

JSPXXMMLL tetechnologychnology elements, which determine how the page construcconstructsts dynamic content

The packages involvinvolveded in creatcreatinging JSP pages are javax.el,, javax.servlet.jsp,, javax.servlet.jsp.el, and javax.servlet.jsp.tagext, though yyouou will rarely havehave to importimport these directly.directly. A JSP page can be as sim ple as a bit of HTML with one snippet of JSP code and the .jsp ex extensiontension of the page nam e.e. aavvaa..ssuunn..ccoomm//jjsspp__uuttiillss//PPrriinnttPPaaggee..jjsspp??uurr…… 22//77

1111//3300//22001100 JJaavvaa TTeecchhnnoollooggiieess ffoorr WWeebb AApppplliiccaattiioonnss

For instance, yyouou can creatcreatee a wwebeb s ite of JSP ttechnologyechnology pages that use one snippets nippet of code to include the header.html file, which contains the site navigation. This way, when you change a link to a button in the navigation, you make the change in only one file, and that ffileile loads into all the pages on the sitesite that havehave this code snippet:snippet:

<%@ include file="header.html" %>

That line of code works ververyy mmuchuch like a sserverver-sideer-side include,include, if youyou are familiarfamiliar with those. Because this web page is now a JSP page, yyouou could als o go on to add mmoreore JavaJava technology code to createcreate dyndynamamicic web content, such as pollspolls,, formms,s,for ways to enter or retrieve data from a database, and so forth.

Take a look at two helpful documents about creatingcreating JSP pages:

JavaServer Pages (JSP) v2.0 Syntax Reference JavJavaServeraServer Pages Technology -- Frequently AAskeskedd QuestionsQuestions

JavaServer Pages StandStandardard Tag Library

The JavaServer Pages Standard Tag Library (JSTL) encapsulates core functionality common to many JSP technology- based applications. Instead of mixing ttagsags from numnumerouserous vendors in your applicatapplications,ions, you employ a singlesingle sstandardtandard set of tags. This s tandardiztandardizationation allows yyouou to deploy yyourour applications on any JSP containercontainer that supports JSTL and mmakesakes itit more likely tthathat the implemimplementatentationion of the tags is optimized.

JSTJSTLL has iteratiteratoror and conditional tags for handling flow control, ttagsags for manipmanipulatingulating XMMLX L documents,documents, internationalizationinternationalization tags, tags for accessaccessinging databases usinusingg SQLSQL,, and ttagsags for commonlycommonly used functions.

The packages you can access for ususinging JSTL are javax.servlet.jsp.jstl.core,, javax.servlet.jsp.jstl.fmt,, javax.servlet.jsp.jstl.sql, and javax.servlet.jsp.jstl.tlv..

Learn mmoreore about JSTL.

JavaServer Faces Technology

JavJavaServaServerer Faces technology is a UUII framework for building web applapplications.ications. The mainmain componentscomponents of JavaServJavaServerer Faces technology invinvolvolvee a GUI component framework, a flexibleflexible m odel for rendering comcomponentsponents in vvariousarious mmarkuparkup languages and technologies, and a standard RenderKit for generating HTML markup.

This functionality is available through standard Java APIs and XML-based configuration files. In addition, Sun Java Studio Creator IDE leverages JavaServer Faces technology in its drag-and-drop GUI tools, allowing you to use the technology without having to write or understand the underlying code. See also "Getting Started With Sun Java Studio Creator."

Java MessaMessagege ServiServicece API

Messaging is a memethodthod of commcommunicationunication betweenbetween sosoftftwareware components or applications. A mes saging saging system is a peer- to-peer ffacilityacility. InI. n other words, a memessss aging client can send m ess ages to and receivereceive messssme ages from any otherother client. Each client cconnectsonnects to a mes saging agent that providesprovides facilitiesfacilities for creating,creating, sending,sending, receiving,receiving, and reading messmessages. By combining Java technology with enterprise messaging, the Java Message Service (JMS) API provides a powerful tool for solving enterprise computing problems.

EnterEnterpriseprise mes saginsagingg providesprovides a reliable, flexibleflexible s erverviceice for the exchangeexchange of businbusinessess data throughout an enterprise.enterprise. The JMJMSS AAPIPI adds to this a commcommonon APIAPI and providerprovider framework that enables the developmdevelopmentent of portableportable mesmessagesage-based-based applications in the JavJavaa programm ing language. An exexampamplele of how JMS might be usedused is an application that keeps track of inventory for an auto manufacturer.The inventory component can send a message to the factory component when the inventory level for a product goes below a certain level, so the factory can make more cars. The factory component can send

senda mmessess mmessess age agesto the to partparts theirs comcomponents ownponents invinventoryentory ssoo and that order tthehe factfactory componentscomporyonents can ass toemble emb updatele the their parts inventoriesinv itentories needs.The and partspartto orders componentscom newponents parts in from turn can suppliers and so forth.

The JMJMSS APIAPI improvesimproves programmprogrammerer productivityproductivity by defining a commoncommon set of mmessess aging concepts and programmingingprogramm

aavvaa..ssuunn..ccoomm//jjsspp__uuttiillss//PPrriinnttPPaaggee..jjsspp??uurr…… 33//77

1111//3300//22001100 JJaavvaa TTeecchhnnoollooggiieess ffoorr WWeebb AApppplliiccaattiioonnss strategies that all JMJMS technologytS echnology-compliant-compliant messaging s yystemsstems will ssupport.upport.

Learn m ore aboaboutut the JMS AAPI.PI.

JavaMail API and the JavaBeans Activation Framework

Web applications can use the JavaMail API to send email notifications. The API has two parts: an application-level interface that tthehe application comcomponentsponents useus e to sendsend emailemail and a servsa erviceice providerprovider interface.interface. ServiceService providersproviders implemimplementent particular particular email protocols, such as SMTP. Several service providers are included with the JavaMail API package, and others are available separately. The Java EE platform includes the JavaMail extension with a service provider that allows application componentcomponentss to send email.

In conjunconjunctionction wiwithth the JavaMailJavaMail extextensension,ion, you mightmight use the JavaBeans AActivctivationation FramFrameworkework (JAF)(JAF) API.API. This API provprovidesides standard sservervicesices to determine the tytypepe of aann arbitrary piece of data, encapsulencapsulateate access to it, discover thethe operations avavailableailable on it, and create the appropriate component babasedsed on JavaBeansJavaBeans component architecturearchitecture (Jav(JavaBeansaBeans component) to perfperformorm thosthosee operations.

The JavaMail API is now open source. See the GlassFish Project -- JavaMail home page.

Learn mmoreore ababoutout the JavaMailJavaMail AAPIPI and the JAF.

Java API for XML Processing

The JavJavaa AAPIPI fforor XXMMLL ProcesProcessisingng (JAX(JAXP),P), part of the JavJavaa SE platform, ssupportsupports the procesprocesssinging of XMLXML documdocumentsents ussingu ing the Docum ent Object Model (DOM(DOM),), the SimSimpleple API forfor XMLXML (SA(SAXX),), and ExtExtensensibleible StyleslesheetSty heet LanguagLanguagee TransformaTransformationstions (X(XSLT).SLT).

JAJAXXPimplementation.P enables applications to parse and transform XXMMLL documentsdocuments independentindependent of a particular XMML-processiX L-processingng

JAJAXXPP also provides namespacenamespace ssupport,upport, which lets you work withwit schemassh chemas that mimightght otherwisotherwisee havehave namingnaming conflicts.s.conflict Designed to be flexible, JAXP lets you use any XML-compliant parser or XSL processor from within your application and supports the W3C schema.

Learn m ore aboaboutut JAJAXXP.P.

The Java AAPIPI for XXMMLL Web Services (JAX(JAX-WS)-WS) is nnowow an open-source projectproject at java.java.netnet and is alsalsoo a key part of the GlasGlasssFishFish pproject.roject. See alsalsoo Introducing JAXJAX-WS-WS 2.0 WithWith the Java SE 6 Platform,Platform, Part 1.1.

JDBC API

The JDBC AAPIPI allows yyouou invokeinvoke database SQL commandscommands from JavaJava programm ing language mmethods.ethods. YouYou can ususee the JDBC API in a servlet, JSP technology page, or an enterprise bean when you need to access the database.

The JDBC AAPIPI has two parts: an application-levapplication-levelel interfaceinterface that application components us e to access a database and a seservrviceice provider interface to attach a JDJDBCBC driver to tthehe JavJavaa EE platformplatform..

The left sidsidee of Figure 2 showsshows how a client m akes a direct call to thethe application servserver,er, usually throughthrough a servservletlet or JSP page, and that data is then ssentent to tthehe database managemenmanagementt system (DBMS)(DBMS) server.server. TThehe right sideside of Figure 2 showsshows how a drivdriverer translates JDBC calls into the middlemiddlewareware vendor'svendor's protocol.

aavvaa..ssuunn..ccoomm//jjsspp__uuttiillss//PPrriinnttPPaaggee..jjsspp??uurr…… 44//77

1111//3300//22001100 JJaavvaa TTeecchhnnoollooggiieess ffoorr WWeebb AApppplliiccaattiioonnss

Figure 2: Browser to Database Model

Learn more about the JDBC API.

Java Persistence API

The JavJavaa PersisPersistencetence AAPIPI is a Java ttechnologyechnology standards-based solution for persistence.persistence. PersisPersistencetence uses an object- relational mappmappinging approach to bridge the gap betweenbetween aann object-orientedobject-oriented mmodelodel and a relational database. JavaaJav technology persistencepersis tence consiconsistssts of threethree areas:

The Java PersisPersistencetence APAPII The query language ObjectObject-relational-relational mappimappingng mmetadatetadataa

Read the Java Persis tence API FFAAQ.Q.

Java Naming and Directory Interface

The Java Naming and Directory Interface (JNDI) provides naming and directory functionality, enabling applications to access mulmultipletiple naminamingng and directory services. It provprovidesides applications withwith methods for performingperforming standard directory operations, such as assassociatingociating attattributesributes with objects and ssearchingearching for objectsobjects us ing their attattributes.ributes. Using JNDI,JNDI, a web application can store and retrieve any type of named Java technology object, allowing applications to coexist with many legacy applicaapplicationstions and systsystemsems..

NamNaminging servservicesices provide applicationapplication clients, enterpriseenterprise beans,beans, and web componentscomponents with access to a JNDI naming envenvironment.ironment. A naming enenvvironmenironmentt allows the devdevelopereloper to customizizecustom e a component without having to access or change the component's ssourceource code. A container implemimplementsents the component'component'ss envenvironmentironment and providesprovides it to the component as aa JNDI naming context.

Learn more abouaboutt JNDI.

Other TeTechnolochnologiesgies to ConConsider sider

YYouou mmightight want to consider ususinging the following other technologiestechnologies in your web application,application, depending on the application'sapplication's complexity:

J2EE Connector AArchitrchitecturecture:e: Tools vvendorsendors and s yystemstem integratorsintegrators use this aarchitrchitecturecturee to create resourceresource adapters that support access to enterprenterpriseise information syystemss stems that ccanan be plugged inin to any JavaJava EE technology-basedtechnology-based product. JavJavaa Authentication andand AuthorizAuthorizationation ServServiceice (JAA(JAAS):S): JAAASJA S provides a wayway for a Java EE technology-technology-basbaseded applicaapplicationtion to authenticauthenticateate and authorizauthorizee a s pecific user or group of users to run it. Java API for XML Registries (JAXR): JAXR lets you access business and general-purpose registries over the web. JavJavaa ArchitectureArchitecture for XMXMLL BindBindinging (JAXXB):(JA B): JAXXBJA B provides a convenient wayway ttoo bindbind an XXMML ssL chema chema to a representationrepresentation in applications wwrittrittenen in the JavaJava programmprogramminging language. SOAP with Attachments API for Java (SAAJ): SAAJ is a low-level API on which JAX-WS and JAXR depend.

aavvaa..ssuunn..ccoomm//jjsspp__uuttiillss//PPrriinnttPPaaggee..jjsspp??uurr…… 55//77

1111//3300//22001100 JJaavvaa TTeecchhnnoollooggiieess ffoorr WWeebb AApppplliiccaattiioonnss JavJavaa TransactionTransaction API (JTA(JTA):): JTJTAA provides a standard interfaceinterface for demarcatingdemarcating transactionstransactions..

Development Tools

IntIntegratedegrated developmdevelopmentent envenvironmentsironments (IDEs) can speed the process of devdevelopingeloping and testing web applications.applications. It'sIt's no wonder that developers move to an IDE, but which one is right for you? Which features do you need? supports three IDEs for the Java platform: NetBeans IDE, Sun Java Studio Creator IDE, and Sun Java Studio Enterprise IDE.

NetBeans IDE

NetBeans IDE is free and open ssource.ource. TThishis IDE is writtrittenw en in the JavaJava programm ing language and providesprovides the servicesservices commcommonon to desktop applications, such as windowwindow and mmenuenu manamanagement,gement, settings storage,storage, and so forth. It is alalsoso the first IDE to fully support JDK 5.0 features. In addition, it supports wwebeb tools, includingincluding the NetBeans IDE EnterEnterpriseprise Pack, which adds eveveryerythingthing youyou need to imimmedmediatelyiately start writing, testing, and debugging JavJavaa technology-basedtechnology-based web applications.

The pack provprovidesides vvisuisualal desdesignign tools for Unified ModelingModeling Language (UML) modeling,modeling, XMMLX schemasL chema creatcreation,ion, modificatmodification,ion, and visualizatvisualization,ion, as well as developmdevelopmentent of secure, identity-enabledidentity-enabled web services.

Sun Java Studio Creator IDE

Sun JavJavaa Studio Creator IDE is great for quick and easy webweb applicationapplication developmdevelopment.ent. InIn addition, this IDE is built on the NetBeans IDE, starting with a subset of the functionality and extending it.

Sun JavJavaa Studio Creator IDE allows yyouou to build applications visually. TheThe programminprogrammingg part is cleanly separated frfromom the UI. WitWithh Sun Java StudioStudio Creator IDE, the IDE ttakesakes care of a lot of the repetitive coding behibehindnd the UI.UI.

The rapid visual drag-and-drop features are bas ed oonn JavJavaServaServerer Faces technology,technology, which is a framework for building UIs for web applications. A GGUIUI is used for manipulating JavaServJavaServerer Faces components,components, as well as vvisualisuallyly definingdefining page flow. There'There's as alsolso graphical support for easily workingworking with databases and web sservervices.ices.

Sun Java SStudiotudio EEnterprisenterprise IDE

Sun JavJavaa Studio Enterprise IDE is a powerful ssetet of tools that providesprovides an integrated framework for enterprise-grade, rapid web application development. It offoffersers enhancedenhanced debugging and devdevelopmelopmentent support for web servservicesices andand for devdevelopmelopmentent of JavaJava EE technologytechnology-based-based applications.

Sun JavJavaa Studio EnterpriseEnterprise IDE is builtbuilt on and extendsextends the NetBeans IDE. ItIt also enablesenables smsmart code editing, such as completing your code for yyou,ou, with refactrefactoring,oring, renaming objects throughout an application. It also enablenableses performance tuning -- ensuring better use of memmemoryory and ssoo forthforth -- of applicationsapplications with an optimal end- user experience.experience.

Sun JavJavaa Studio Enterprise IDE providesprovides a model-drivmodel-drivenen analanalyysissis, design,design, and dedevvelopmelopmentent environmentenvironment that leveragesleverages UMUML.L. This integratintegrateded feature reduces complexitcomplexityy and increases vvisuisualal clarity acrossacross software development projects, ensuring that a sound architectarchitectureure is esestablishedtablished and communicommunicatedcated tthroughouthroughout tthehe enterprise.

Now that you are familiar with the many Java technologies that you use in web applications, you are ready to develop your own application. In an upcomiupcomingng sserieseries of articles,articles, you will learn to create web applicatiapplicationsons usingusing Sun JavJavaa Studio Creator IDE, which you can download for free, and learn how to use the JavaJava technologies mentioned in this article. YouYou will first creatcreatee sm all sisimplmplee applications, then work up to more complex prograprograms.ms. In thethe meantime,meantime, follow the links in this article ttoo learn more about the JavJavaa technologies discussdiscusseded in this article.

FForor More Information

Java Message Service (JMS) API JDBC API JavJavaa PersiPersistenstencece API FAFAQQ Getting Started with an Integrated Development Environment (IDE) NetBeans IDE Sun Java Studio Enterprise Sun Java StStudioudio Creator Creator aavvaa..ssuunn..ccoomm//jjsspp__uuttiillss//PPrriinnttPPaaggee..jjsspp??uurr…… 66//77

1111//3300//22001100 JJaavvaa TTeecchhnnoollooggiieess ffoorr WWeebb AApppplliiccaattiioonnss JavaMail AAPIPI Getting Started With Sun JavJavaa Studio CCreator reator Java Web Services Developer Pack (Synopsis of Components)

Rate aandnd RevReviewiew Tell us what you think of the content of this page.

ExcelleExcellentnt GGoodood FFairair Poor

Comments:

Y Youourr email addaddressress (no reply is possibpossiblele withoutwithout an address):address): Sun Privacy Policy

Note: We are not able to respond to all subm ittitteded comments.comm ents.

copyright © Sun Microsystems, Inc

aavvaa..ssuunn..ccoomm//jjsspp__uuttiillss//PPrriinnttPPaaggee..jjsspp??uurr…… 77//77