You are on page 1of 6

10/4/12

Servlet Tutorial: First Servlets

First Servlets
This tutorial is now out of date. Please see the following sites for up-to-date information with downloadable source code. Intermediate servlet and JSP tutorial Advanced servlet and JSP tutorial JSF 2.0 tutorial Apache Tomcat Tutorial -- setup and introduction (includes Eclipse integration) Ajax tutorial GWT tutorial (Google Web Toolkit) jQuery tutorial Java tutorial

1. Basic Servlet Structure 2. A Simple Servlet Generating Plain Text 3. A Servlet that Generates HTML

4. Simple HTML-Building Utilities 5. Servlet and JSP Tutorial: Top 6. Servlet and JSP Training Courses On-site at your company or at public venues.

1. Basic Servlet Structure


Here's the outline of a basic servlet that handles G Trequests. G Trequests, for those unfamiliar with HTTP, are E E requests made by browsers when the user types in a URL on the address line, follows a link from a Web page, or makes an HTML form that does not specify a M T O . Servlets can also very easily handle P S requests, which EHD OT are generated when someone creates an HTML form that specifies M T O = P S " We'll discuss that in later EHD"OT. sections.
ipr jv.o* mot aai.; ipr jvxsrlt* mot aa.eve.; ipr jvxsrltht.; mot aa.eve.tp* pbi casSmSrltetnsHtSrlt{ ulc ls oeeve xed tpeve pbi vi dGtHtSrlteus rqet ulc od oe(tpeveRqet eus, HtSrltepnersos) tpeveRsos epne trw Srltxeto,IEcpin{ hos eveEcpin Oxeto / Ue"eus"t ra icmn HT haes(..cois / s rqet o ed noig TP edr eg oke) / adHM fr dt (..dt teue etrdadsbitd / n TL om aa eg aa h sr nee n umte) / Ue"epne t seiyteHT rsos ln adhaes / s rsos" o pcf h TP epne ie n edr / (..seiyn tecnettp,stigcois. / eg pcfig h otn ye etn oke) Pitrtrot=rsos.eWie(; rnWie u epnegtrtr) / Ue"u"t sn cnett bosr / s ot o ed otn o rwe } www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-First-Servlets.html
1/6

10/4/12

Servlet Tutorial: First Servlets

} }

(Download template source code -- click with the right mouse on the link or hold down SHIFT while clicking on the link.) To be a servlet, a class should extend HttpServlet and override d G tor d P s (or both), depending on whether oe oot the data is being sent by G Tor by P S . These methods take two arguments: an HttpServletRequest and an E OT HttpServletResponse. The H t S r l t e u s has methods that let you find out about incoming information tpeveRqet such as FORM data, HTTP request headers, and the like. The H t S r l t e p n ehas methods that lets you tpeveRsos specify the HTTP response line (200, 404, etc.), response headers (C n e t T p , S t C o i , etc.), and, otn-ye e-oke most importantly, lets you obtain a PrintWriter used to send output back to the client. For simple servlets, most of the effort is spent in p i t nstatements that generate the desired page. Note that d G tand d P s throw two rnl oe oot exceptions, so you are required to include them in the declaration. Also note that you have to import classes in j v . o(for P i t r t r etc.), j v x s r l t(for H t S r l t etc.), and j v x s r l t h t (for aai rnWie, aa.eve tpeve, aa.eve.tp H t S r l t e u s and H t S r l t e p n e Finally, note that d G tand d P s are called by the tpeveRqet t p e v e R s o s ). oe oot s r i emethod, and sometimes you may want to override s r i edirectly, e.g. for a servlet that handles both evc evc G Tand P S request. E OT

2. A Simple Servlet Generating Plain Text


Here is a simple servlet that just generates plain text. The following section will show the more usual case where HTML is generated.

2.1 HelloWorld.java
You can also download the source or try it on-line.
pcaehl; akg al ipr jv.o* mot aai.; ipr jvxsrlt* mot aa.eve.; ipr jvxsrltht.; mot aa.eve.tp* pbi casHlool etnsHtSrlt{ ulc ls elWrd xed tpeve pbi vi dGtHtSrlteus rqet ulc od oe(tpeveRqet eus, HtSrltepnersos) tpeveRsos epne trw Srltxeto,IEcpin{ hos eveEcpin Oxeto Pitrtrot=rsos.eWie(; rnWie u epnegtrtr) otpitn"el Wrd) u.rnl(Hlo ol"; } }

2.2 Compiling and Installing the Servlet


Note that the specific details for installing servlets vary from Web server to Web server. Please refer to your Web server documentation for definitive directions. The on-line examples are running on Java Web Server (JWS) 2.0, where servlets are expected to be in a directory called s r l t in the JWS installation hierarchy. However, I eves placed this servlet in a separate package (h l ) to avoid conflicts with other servlets on this server; you'll want to al
www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-First-Servlets.html 2/6

10/4/12

Servlet Tutorial: First Servlets

do the same if you are using a Web server that is used by other people and doesn't have a good infrastructure for "virtual servers" to prevent these conflicts automatically. Thus, H l o o l . a aactually goes in a subdirectory elWrdjv called h l in the s r l t directory. Note that setup on most other servers is similar, and the servlet and JSP al eves examples in the tutorial have also been tested using BEA WebLogic and IBM WebSphere 3.0. WebSphere has an excellent mechanism for virtual servers, and it is not necessary to use packages solely to prevent name conflicts with other users. If you've never used packages before, there are two main ways to compile classes that are in packages. One way is to set your C A S A Hto point to the directory above the one actually containing your servlets. You LSPT can them compile normally from within the directory. For example, if your base directory is C \ a a e S r e \ e v e sand your package name (and thus subdirectory name) is h l , and you were on :JvWbevrsrlt al Windows, you'd do:
DS stCASAHC\aaeSre\eves%LSPT% O> e LSPT=:JvWbevrsrlt;CASAH DS c C\aaeSre\eveshl O> d :JvWbevrsrlt\al DS jvcYuSrltjv O> aa oreve.aa The first part, setting the C A S A H you probably want to do permanently, rather than each time you start a new LSPT, DOS window. On Windows 95/98 you'd typically put the "s t C A S A H ..." statement in your a t e e . a e LSPT= uoxcbt file somewhere after the line that set the C A S A Hto point to s r l t j rand j p j r On Windows NT, LSPT eve.a s.a.

you'd go to the Start menu, select Settings, select Control Panel, select System, select Environment, then enter the variable and value. Note also that if your package were of the form n m 1 n m 2 n m 3rather than simply ae.ae.ae n m 1as here, you'd still have the C A S A Hpoint to the top-level directory of your package hierarchy (the one ae LSPT containing n m 1 a e ). A second way to compile classes that are in packages is to go to the directory above the one containing your servlets, and then do "j v c d r c o y Y u S r l t j v " (Windows; note the backslash) or "j v c aa ietr\oreve.aa aa d r c o y Y u S r l t j v " (Unix; note the forward slash). For example, suppose again that your base ietr/oreve.aa directory is C \ a a e S r e \ e v e sand your package name (and thus subdirectory name) is h l , and :JvWbevrsrlt al you were on Windows. In that case, you'd do the following:
DS c C\aaeSre\eves O> d :JvWbevrsrlt DS jvchl\oreve.aa O> aa alYuSrltjv

Note that, on Windows, most JDK 1.1 versions of j v crequire a backslash, not a forward slash, after the aa directory name. This is fixed in JDK 1.2, but since many Web servers are configured to use JDK 1.1, many servlet authors stick with JDK 1.1 for portability. Finally, another advanced option is to keep the source code in a location distinct from the .class files, and use j v c "- " option to install them in the location the Web server expects. a a 's d

2.3 Running the Servlet


With the Java Web Server, servlets are placed in the s r l t directory within the main JWS installation eves directory, and are invoked via h t : / o t s r l t S r l t a e Note that the directory is s r l t , tp/hs/eve/eveNm. eves plural, while the URL refers to s r l t singular. Since this example was placed in the h l package, it would be eve, al invoked via h t : / o t s r l t h l . e l W r d Other Web servers may have slightly different tp/hs/eve/alHlool. conventions on where to install servlets and how to invoke them. Most servers also let you define aliases for servlets, so that a servlet can be invoked via h t : / o t a y p t / n - i e h m . The process for doing tp/hs/n-ahayfl.tl this is completely server-specific; check your server's documentation for details.
www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-First-Servlets.html 3/6

10/4/12

Servlet Tutorial: First Servlets

3. A Servlet that Generates HTML


Most servlets generate HTML, not plain text as in the previous example. To do that, you need two additional steps: tell the browser that you're sending back HTML, and modify the p i t nstatements to build a legal Web page. rnl The first step is done by setting the C n e t T p response header. In general, headers can be set via the otn-ye s t e d rmethod of H t S r l t e p n e but setting the content type is such a common task that there is eHae tpeveRsos, also a special s t o t n T p method just for this purpose. Note that you need to set response headers before eCnetye actually returning any of the content via the P i t r t r Here's an example: rnWie.

3.1 HelloWWW.java
You can also download the source or try it on-line.
pcaehl; akg al ipr jv.o* mot aai.; ipr jvxsrlt* mot aa.eve.; ipr jvxsrltht.; mot aa.eve.tp* pbi casHloW etnsHtSrlt{ ulc ls elWW xed tpeve pbi vi dGtHtSrlteus rqet ulc od oe(tpeveRqet eus, HtSrltepnersos) tpeveRsos epne trw Srltxeto,IEcpin{ hos eveEcpin Oxeto rsos.eCnetye"ethm"; epnestotnTp(tx/tl) Pitrtrot=rsos.eWie(; rnWie u epnegtrtr) otpitn"!OTP HM PBI \-/3/DDHM 40"+ u.rnl(<DCYE TL ULC "/WC/T TL . "rniinl/N"\"+ Tastoa/E\>n "HM>n + <TL\" "HA>TTEHloWW/IL>/ED\"+ <ED<IL>el W<TTE<HA>n "BD>n + <OY\" "H>el WW/1\"+ <1Hlo W<H>n "/OY<HM>) <BD>/TL"; } }

3.2 HelloWWW Result

www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-First-Servlets.html

4/6

10/4/12

Servlet Tutorial: First Servlets

4. Simple HTML-Building Utilities


It is a bit cumbersome to generate HTML with p i t nstatements. The real solution is to use Java Server Pages rnl (JSP), which is discussed later in this tutorial. However, for standard servlets, there are two parts of the Web page (D C Y Eand H A ) that are unlikely to change and thus could benefit from being incorporated into a simple utility OTP ED file. The D C Y Eline is technically required by the HTML spec, and although most major browsers ignore it, it is very OTP useful when sending pages to formal HTML validators. These validators compare the HTML syntax of pages against the formal HTML specification, and use the D C Y Eline to determine which version of HTML to check OTP against. Their use is very highly recommended both for static HTML pages and for pages generated via servlets, so the use of D C Y Eis well worth the effort, especially if it can be easily incorporated into a servlet utilities class. OTP In many Web pages, the H A line contains nothing but the T T E although advanced developers may want to ED IL, include M T tags and style sheets. But for the simple case, I'll create a method that takes a title as input and returns EA the D C Y E H A , and T T Eentries as output. Here's the code: OTP, ED IL

4.1 ServletUtilities.java (Download source code)


pcaehl; akg al pbi casSrlttlte { ulc ls eveUiiis pbi sai fnlSrn DCYE= ulc ttc ia tig OTP "!OTP HM PBI \-/3/DDHM 40Tastoa/E\>; <DCYE TL ULC "/WC/T TL . rniinl/N"" pbi sai Srn haWtTteSrn tte { ulc ttc tig edihil(tig il) rtr(OTP +"n + eunDCYE \" "HM>n + <TL\" "HA>TTE"+tte+"/IL>/ED\"; <ED<IL> il <TTE<HA>n) } / Ohruiiiswl b sonltr. / te tlte il e hw ae.. }

4.2 HelloWWW2.java (Download source code)


Here's a rewrite of the HelloWWW class that uses this.
5/6

10/4/12

Servlet Tutorial: First Servlets

pcaehl; akg al ipr jv.o* mot aai.; ipr jvxsrlt* mot aa.eve.; ipr jvxsrltht.; mot aa.eve.tp* pbi casHloW2etnsHtSrlt{ ulc ls elWW xed tpeve pbi vi dGtHtSrlteus rqet ulc od oe(tpeveRqet eus, HtSrltepnersos) tpeveRsos epne trw Srltxeto,IEcpin{ hos eveEcpin Oxeto rsos.eCnetye"ethm"; epnestotnTp(tx/tl) Pitrtrot=rsos.eWie(; rnWie u epnegtrtr) otpitnSrlttlte.edihil(HloWW)+ u.rnl(eveUiiishaWtTte"el W" "BD>n + <OY\" "H>el WW/1\"+ <1Hlo W<H>n "/OY<HM>) <BD>/TL"; } }

Sitemap for coreservlets.com


Training
About the Instructor Course Reviews Intermediate Servlet & JSP Training Courses Advanced Servlet & JSP Training Courses JSF 2.0 Training Courses Ajax Training Courses Java Training Courses Customized On-Site Training Courses Public Training Course Schedule

Tutorials
Apache Tomcat Tutorial Intermediate Servlets & JSP Tutorial Advanced Servlets & JSP Tutorial Jakarta Struts Tutorial JSF 2 Tutorial Java Tutorial Ajax Tutorial jQuery Tutorial GWT Tutorial

Programming Resources
Specifications & Documentation Servers IDEs Java-Related Jobs JavaServer Faces (JSF) Books Web Hosting Providers Java Programming Resources

Books
Core Servlets & JSP 2nd Ed. M ore Servlets & JSP Core Web Programming Core Servlets & JSP 1st Ed. Core Servlets & JSP E-Book M ore Servlets & JSP E-Book

Consulting
Our consulting services We are hiring!

Jobs

www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-First-Servlets.html

You might also like