Download as pdf
Download as pdf
You are on page 1of 15
ns. How to Install Tomeat 7 (on Windows, Mac and Ubunty) and Got Started with Java Seret Programming How to Install Apache Tomcat 7/8 ser ranterraca 1b aude tomatoe (on Windows, Mac, Ubuntu) eee tous and 23 st cong oman Get Started with Java Servlet 26 Sti? 6 ite Weli-wot 2:7 STEP 7. Wit a Database Serv Programming 28 (Advance) Deploying Serlt 3, How to Debug? Ths tutors an be completed in 8 how session ‘Ths instaltion and confguration guide is appkabl to Tomcat 7/8, and posiby the earr versions Take note that Tomes 8 requires JOK 17. wil NOT work wih JDK 15. 1, Introduction 1.1 Web Appl ation (Webapp) Aub application ior webapp), une standalone appeaton runs over the Internet, ample of webapps are goog, amazon ebay, facebook and twtr. [A.wobapp is typialy a 3-tir (or mut in clint server database application run over the Internet 2s ilstratd in the clagram below. I comprises fe components 1. HTTP Server: Eg, Apache HTTP Server, Apache Tomeat Server, Mics Intemat Information Server BS}, nginx Google Web Server (GW, and others. 2. HITP Client (or Web Browser): Eg, Intamet Explorer (MSI, FireFox Chrom, Safar nd others 3, Database: Eg, Open-source MySQL, Apache Darby, mSQl, SQlite, PostgreSQL, OpenOlfice's Bat; Commercial Oracle, BM D2, SAP Sybase, MS SQL ‘Server, MS Acces: and others 4, Client-Side Programs: couls be writen in HIML Form, JavaScript V8Serpt lah, an others 5. Server-Side Programs: could be writen in ava Servle5P, ASP, PHP, Pel, Python, CSL and others, wart. ecu 9 homelehchualprogranringibowd/Toreat HowToind ws ns. How to Install Tomeat 7 (on Windows, Mac and Ubunty) and Got Started with Java Seret Programming HTTP Client HTTP HTTP Server (Browser) {over TCP/IP) (hostname :port) aa Request Message Programs HTML pages, |= — Forms, Applets Gay <_Besponee Menge aa TCP/IP Network ‘Server-side Programs ‘Application “Te Presentation ssl Session Transport TCP | Multiplexing (Port), Re-transmission Network IP | Addressing (IP Adcress), Routing Data Link | | TEEE802.4« Physical The typical usecase is ‘Aus v a web browser (HTTP con ssues a URL request to an HTTP server ta start a webapo. ‘A cbant-side program (ch a¢ an HTML fori dd int chins rows ‘The user fil up the quay ctr inthe frm. The cess program sends the qury parameters to a sererside program, ‘The server-side program reeves the query parameters, queras the database and returs the query result tothe cent. “The cnt-side program ispys the query resukon the browser. The proces epee 1.2_ Hypertext Transfer Protocol (HTTP) ‘HTTP san oppication layer protocol runs over TCP/IP. The IP provides support for routing and adcresing (vi an unique IP adress for machines on the Internet hie TCP supports multiplexing vi G4K ports rm port number 0 to 65535, The default prt number ssgned to HTTP ie TC por 80, = HTP san esynchonous request response application layer protocol. clon sends 3 request message tothe server. The server then retuns a response message tothe cent, + HIT sa pull protocol,» dent pul a page rom the sewer (stead of server pushes pages to the clans = The syntax of the messages defined inthe HTP soxfation, wart. ecu 9 homelehchualprogranringibowd/Toreat HowToind 218 ns. How to Install Tomeat 7 (on Windows, Mac and Ubunty) and Got Started with Java Seret Programming Request Message GET /hone.heml HTTP /2.1 Host: xyz.com HTTP Client(s) Connection: Keep-Alive http://xyz.com/homehtml User-Agent: Mozilla/4.0 Accept: image/gif, image/jpeg | : = "=== blank line 2 f Gemcty touyy HTTP Server al R M 1 server-side cliente | jesponse Message ! sisal] bene HrTP/1.1 208 OK a Date: =) (|_| server: apache/2.0.45 Last-Hodified: Content-Length: 105 — ContentType: text/htal = blank Line - | HTTP over TCP/IP 1.3 Apache Tomcat HTTP Server ‘Apache Tomcat sa Jva-capabe HTTP server, which could execute specal Java programs known 3s Java Serut and JavaServer Pages USP) Ts the offal Reference Implementation (R) for Jv Setlets and iseaServer Pages USP technologies Tomcat an open-source projec, under the "Apache Software Foundation’ which ao provides the most use open-source, idustakstrength Apsche HTTP Server The mother site far Temeat is htp/tomeat apache ‘Aherativaly, you en Fd tomeat vis the Apache mother ste @ hip /isiuspacrecrs Tomcat was otgnaly writen by James Duncan Davison then working in Sun, 1998, based on an eater Sun's Server calle Java Web Sever UWS}. It began a version 3.0 after SWDK 21 i replaced, Sun subsequently made Tomcat open-source and gave it to Apache The various Tomest releases re Tomcat 3 (1999): for Servlet 22 and SP 11, Teomeat (2001) A or Servlet 23 and JSP 12. Tomeat (2002): for Seret 24 and iS? 20, Tomeat 6/2006}: Al for Serlet 25 and SP 21. Tomeat 7x (2010} A for Srl 3.0, 8P 22 and EL 22. Tomcat 8 (2010): Al for Servlet 3.1, JSP 23, 1 3.0 and Java WebSocket 10. Tomest san HTTP appleaton runs over TCPAP. In ather words, the Tomeat saver tuns on a specife TC? port in a speccP address. The deft TCP port, umber for HTTP protecl ie 89, which fused forthe production HTTP server Far test HTTP saver, you can chagse any unused port number between 1024 and 68535; hil port aumbers 1-1023 are reserves 2. How to Install Tomcat 7 and Get Started with Java Servlet Programming 2.1 STEP 1: Download and Install Tomcat For Windows 2. Got htipy/amcatapachecrg + Downloads > Tomcat 80 > °8.0. x)" where or) the atest upgrade number) = Bing Distbations > {Core “rp" package (eg, "apache-toncat-8.8. (ex) .2ip%, about 8 MBL 2, UNZIP into a dietary of yout choice. 0 NOT unzip onte the Desktop (because its path is hard to leat). suggest using "és yprosect’ Tomcat wil be unzipped into directory “d:\nyproject\apache-toncat-8.8. ex)". For ease of use, we shall shorten and rename this rectory to "4: \nyproject\toncat", Take note of Your Tomcat installed Directory, Hereafter, shall refer tothe Tomes instal drectory {38 CTONCAT_HOME> (or Download > Tomaat 80 > °8.8.(xx}* (where (xx) denotes the lest upgrade number) > Binary lstrbuton » Core “tar” package eg, ‘apache-toncat-8.8. (xx), tar.gz’ about § MB) 1. Golo ~/Dountoads", doubk- for Contol Panel > System = (ists/7/8) Advanced systam settings Snitch to"Acvanced’ tab > Envizanment Variable System Variables "New fr “Ed for modifeston) = In “Vorsble Name, enter "IAVAHOWE” © In “Votble Valie, enter your JOK. instald rectory (eg, “c:\Program Fies\ava\jakt.7.0_ 008), 4. Tovey, RESTART 3 CMO shall (nea to eftesh the environment and issue AVA sOWE-es\Progran Fes\2ava\él.7.0 ¢ee) For Mac Skip this step. No nzed te do anything, 2.3. STEP 3: Configure Tomcat Server The Tomeat configuration les ae located inthe “cont” sub-dectry of your Tomcat installed dreary, e9,“ \nyproject \tomcat\cont” (for Windows) or wart. ecu 9 homelehchualprogranringibowd/Toreat HowToind ans ns. How to Install Tomeat 7 (on Windows, Mac and Ubunty) and Got Started with Java Seret Programming ‘ApphicatLons/tencat” fr Mac). Thre are configuration XML Ales 3. contert.xnl 4, toncat-users.xn] Make 3 BACKUP ofthe configu on les before you proceed Step 3(a) “conf\server.xal" - Set the TCP Port Number etl for Mac to open the configuration fle "server.xml", under the Uses programming tet exitor fg. NotePad +, TentPad for Windows of gE ed, ‘cont sub-decory of Tome istled rectory The default TCP port number configured in Tomcat & 2080, you may choose any number between 1024 and 65535, which fs not used by an esting ‘pplication. We shall choose 9999 inthis article Far production server, you should use port #0, which pre-assigned to HTTP server as the default port number) Locate the follwing nes, and change port="8880" to port="9999 iss A *Conector” repress an endpoint by whieh requests are received Java HTT Conector! oes/contig/http.Ntal (blocking & non-blocking) ra OP. Connector: /does/cantig/aipchial ira (srteyAsP) Connector: fdses/ape-hint Define a ran-SSL HITP/I-1 Conmector on port 8886 Step 3(b) “conf\web.xnl” - Enabling Directory Listing ‘Again use a programming te etr to open the configuration le'web.x", under the "cont sub-directory of Tomcat installed decry. We shall enable directory listing by changing “Listings fom "false! to “true” forthe “default” servlet. This is handy for production system for secur ressons system but not for Locate the following Ines ancl change om “false” ‘9 “trve" ‘paran-value>REuec/paran-valve> Defaultserviet Step 3(<) “conf \context.xn1” - Enabling Automatic Reload ‘We shall add the attrbutereleadable="trve" tothe Context element to enable automaticreload after code changes. Again this is handy for test system but not fr production de tothe ovarnead of detecting changes. Locate the start element, and change tte «Context reloadable="trve"> Step 3(4) (Optional) “conf\tomcat-users.xal Enable the Tomeat's manager ty adding the highlghted Ines, inside the ctemeat-users> elements soe" roless"manger-ge/> “This enables the manager GU app for managing Tomes server wart. ecu 9 homelehchualprogranringibowdlToreat HowToint 55 ns. How to Install Tomeat 7 (on Windows, Mac and Ubunty) and Got Started with Java Seret Programming ‘The Toment’s executable programs and scripts are kept in the “bin” sub-directory ofthe Tomat installed directo, eg, A: \nypragect\toncat\bin" (or Windows) or"/Applications/toncat/bin’ for Mad. Step 4(a) Start Server For Windows Lunch a CMD shall Set the curent decry to “ startup For Mac {assume that Tomes is installed in “App Scat fons tomcat” To start the Tomcat server, open 3 new “Trina” and issue 11 charge current directory to Tones Binary directory 3 cd /applications/toncat/6in 17 start twocat server SS Jeataténa.sh run Anew Tomcat console window appears. Study the messages onthe conale. Look ut forthe Tomeat's port number (double check that Temest runing on port 9995). Future eor messages willbe end to this console Systen.out print) issued by your lava serves wil algo be sent ths consol {oor ex opr we Org apache cyte. fostractProteco} start Info: Starting ProtocobMandier (het. b10.9999"] sx ox, naen Hoeniee ee org apache coyote, ADsteactProtecol start Info, Starting Protoceluandier [-ajperio-aea"] vo. x, ween eoproee ee org. apace. catalina. startup.Catalina stort (Skip Unless ...) Cannot Start Tomeat: Read "Yow to Debio ‘Stop 4(b) Start a Client to Access the Server ‘Start browser (as HIT clan) [sue URL “htp://Loeathost 9995" to access the Temeat servers welcome page. The hostname “localhost” th IP ‘deze of 127.8.0.1) fe meant fr loa lop-back testing ise the same machine, For users oh the other machines over the net they have to use the server'P adress of ONS domain name or hostname inthe format af htt: //serverHos toned IPAddress:9999" Apache Tomcati7.0.30 ache ‘Software Foundation hitp://www-apache.ora/ Ityou're seeing this, you've successfully installed Tomcat. Congratulations! ‘Ty isuing URL netp://localhast:9999/ examples to view te sre and SP examples. Try running same ofthe srl examples. (Optcna Try sing URL http: //2ocathost :9999/eanager/ntal torun the Tomcat We Manager. Emer the username and password confguted ear in toncat-users. xn, Step 4(e) Shutdown Server For Windows You can shutdown the tomest serve by her 1. Press itcan the Tomest censor 2, Ran "cTONCRT_HOME> bin shutdown. bat™ srt 11 Change the current directory to Toncat's “bint ya: 11 cranes the current drive G:\> ca Wmpredect\toncat\bin // crange Directory to YOR Toncst’s “bin aivectory wart. ecu sg homelehchualprogranringibowd/Toreat Howard ais ns. How to Install Tomeat 7 (on Windows, Mac and Ubunty) and Got Strtod with Java Seret Programming 11 Shutioun the server ds wyproject\toncat bin shutdown For Mac ‘To shutdown the Tomest sve: 1. Press contre (NOT command: or 2. Run the "/bin/shutdown. sh” sept Open anew “Terminal and issue: Sea fnppileations/toncat/bin- . 11 Shutaoun tho server fenatdoun. oh WARNING: You MUST propetly shutdown the Tomcat. 20 NOTE the xt by pushing the windows “CLOSF button. 2.5. STEP 5: Develop and Deploy a WebApp _ Step 5(a) Create the Di sctory Structure for your WebApp Fest ofall choose a name for your webapp Lets allt ‘helo. Goto Tomeat’s webapps” sub-directory. Create the filming tomeat lrecory structure for you webapp "e110" a ilstrated au 1 Under Temeats webapps", rate your webapp rot decory "helo" (8, “ \webapps\Nelo", os 2, Under "etto', caste 9 subdirectory “WEB-INE fase sensive, 9 “ahoh* not an underscore), Beier “ \webapps\nelLo\MEB-INF, ae 3. Under KEB-INF’, create 2 subsub-drectoy “elasses" (ase semstve, pra fe “ \wobapps\neTTo\WEB-INF\classe=", Bvutax 1h classes You need to keep your web resources (2g, HTML, CSSs, mages, spt, serv, SPs n the proper dratries: helo The called the content root (or dacument base directory) of your webapp. You should keep allyour HTML fe and resources visible to the web users fog. HTMLs, Ss, mages, spt, Ps) under ths context rot hel Lo\WEB-INF* This rectory, though under the context root, snot wsble to the web users This is where you keep your appeaton’s eb descriptor feeb xn 1 "pel Lo\WEb-INF\classes': hii where you keep al the Java classes such as serltcssfles "You shoul RESTART yout Tomeat server to pick up the neo webapp, Check the Toma’ conole to confi that melLo"applition has been propety deoalyed [iS veptoying web application directory D:\nypraject\toncat webapp hele "You can issue the allowing URL to aces the web appeaton “hel Le nttor//lacalhost:9999/heLL0 You shoul see the dretory listing ofthe directory “cTOWCAT_HOME>\webapps\el0" which shall be empty (rove you have enabled rectory sting in web. xn eatin, Step 5(b) Write a Welcome Page reste the fellowing HTML page and save as Hel osone. hel” in your application’ roc cirectry “helo 2 ehenesersteoty Hane Pogse/title>e/nene> “se ineml> You can browse this page by ising this UR netpey//Lacelhost:999/helL/Medlotone. tad wart. ecu 9 homelehchualprogranringibowd/Toreat HowToind ms ns. How to Install Tomeat 7 (on Windows, Mac and Ubunty) and Got Started with Java Seret Programming HTTP Clients (Browser) ‘Tomcat HTTP Server @ hostnane:port: Hello http: //hostnane :port/hel1o/HeloHone. htm HelloHone. tn er ‘Aherativaly, you cn issue an URL t your web application rot "heito netps//localhort:9999/neL10 ‘The sever wiretum the directory tsting of your bate rectory You an then dick on "Hel LoHone. htm” Rename ‘el elome ht to index. hts" and sue a rectory request aga netpe//localhort:9999/neL10 Now: the server wilredret the dractry request to “index. html the root rectory contains an “index. nem instead of serving the econ tng Yu can check out the home page of your peat by issuing nttp:/YourbeersostnanersoAddress:9998/te210 nttpe/YourbeeriortnanePedress:9989/te1l9/Helotarehenl witha vad "YourPeertostnanedriPAldress’ provided that yout peer has started hs tomcat sever and his ews doesnot block your seas, You an use ‘command suchas ‘ipconfig’, wintpefe’, ping’ to fn the P addres. (Skip Unless...) Thelkel eros are “Unable to Connect, trmet Explorer cannot display the webpage’ and 04 Fle Not Found Read "ow to Debug 2.6 STEP 6: Write a "Hello-world” Java Servlet [A serves Java program that runs inside a Java-capbe HTP Server, suchas Apache Tomcat. A web user invokes a servlet by issuing an appropriate URL rom 2 99b browser (HTP cent) Before you proceed shall assume tat you ae fie wth Java Programming and hive installs the followings 1. JDK ead "How to instal DK and Get Startech, 2. A programming txt etor, such as TextPad or Notepads + Read "Programming Text itor’ ora Java IDE such as Eepse or NetBeans (Read "ow to Install Eclipse" or "ow to InstalINetBeans) Step 6(a) Install Servlet API Library Before we can write our fst Srv, we need to install the Sov of Servet APE PI, Sret APL isnot part of JDK or ava SE tht belongs to Java EE Tomnt provides» copy For Windows COPY the Tomeats Senet API jfile lbcated at “ \Lip\serviet-apidar’, (eg. “d:\nyproject\toncat\Lip\serviet= apa) into JDKs extension dvecory at “CIRVA HOME> \JeeXLAB\ext”, eg, “c:\Program Files\Java\ Jak. 7.0\ine\LEB\ext™, For Mac COPY the Servlet APL jartle (ser ‘brary Java/Extension to the JDK: eitenson oiectory st (For Advanced Users Only) Alterative, you could incide the Servet API rfl in the CLASSPATH or the JDK'sextenson rectory: or nthe 4evae| Jave's commandline option “ep \webapps\helLo\NEB-INF\eclasses\Welloserviet. java). Ths serdkt says “Helo”, echos some request information, and prints 3 random number upon each request. 2 / To save as “cimOn_Home>\wetoppenel2o\MEB-INF\cLasses el LServlet. ve" public class Welloserviet extends Htpsonvet ( 7 goveoride 42 public votd docetcntepservietRequest request, HtpServletRestorse response) 3 shows 1aception, Servletiaception { a 11 Set the resoonse MIME type of the response message 2 ‘response-setContentType(“text/Real-);, a [7 Atlacate a output writer to write the response message into the netnork socket a Printarster out » response. getiester(); B 1 ste the cesar sesseg, 26 HTL page ie sut-printin(“entn>"); » n(“enead "); FA an(“eeay>"; a but prinein(“enielLe, workdte/MD>")3. // says Welle 2 17 eho eltane's request dnformstion 2 Dprintin(veppRequest UR: ” + nequest.getRequestiatQ) + °")s, 2 but prinein(~GPatninfo: ~ + request. getPathlnfo() + ""): be Sutcprintin(-cpohenate Adres!" request getRematohdér() + "” + Mathrandon() + “"): Fy but-prinein(“c/badysermeal>") Xe 2 Finaly € a closet}; // Aluays close the ootput setter Compile the source eI loServiet. Java" blo "WelloServiet lass > (Potn-to-the-surce-fite] > Javae Hetloserviet. java (Skip Unless...) ead “Common Eros in Comping Java See” Step 6(¢) Configure Serviet's Request URL in "webapps\he1i0\MEB-INF\web. x01" ‘A.web user invokes » servlet which kept in the wes Server, by suing o request URE fem the browse, We need to configure ths request URL or eur reste the following configura ME web xn fle cal “web-wmt', ad save under ‘Webapps\helLO\NEB-INE" (a, " \webapps\\hel2o\WE: uur ecu 9 homelehchualprogranringibowd/Toreat HowTotind ans ns. How to Install Tomeat 7 (on Windows, Mac and Ubunty) and Got Started with Java Seret Programming 3) xnlnse"htp:// ave. su. con/anl/ns/Javace 4 Rnlneinsi-*httpe/ ont org/2081/20USchens- instance” 5 ent sechealocation="tetp://Jova,sun-con/anl/ne/Savsee Met /Javasun.con/s/ns/ avaee/wsb-app_38.¥58°> 741 To save a5 “hebLo\en-INe Webs 2 ys FA ‘ari-pattert/saybeLloc/uri-oattern> 20 ejserviet-nsplog> In the above configuration, 2 servlet having » cis fle “Mel LoServiet class” is mapped to request URL "/sayhellot Wi an oritory servlet=nane WelloWorle’), under this web application hello". In other words, the complete request URL for thie sewkt ie hnetp://hostnave:port/helo/savhello" ‘Ths eonfguration fle saved under your webapp "helo", appkable onto ths partzubr webapp “hel Lo RESTART your Tomcat server to efresh the ‘web. xf IMPORTANT: For EACH sera, you need to wits & par of cserviet> and elements with a common but arbitrary elements MUST be grouped together and paced IN FRONT of the eservlet-mapping> elements Step 6(4) Invoke the Servlet Torun thi serv, star 3 browse, andisve the request URL configured ate netpey/Lacelhest:999/heLLe/sayhetlo You shall sce the output ofthe servlet splayed in your web bowser arash te browse, you shall sae anew random number upon eich ree In other word the daGet() method ofthe ser runs once pe request ‘Try "Viw Source" to loa atthe cutpu resved by the web usr. Take note thatthe web users receive only the outp ‘out. printin() statements. They have no acess othe servlet programs (whicn may contain confidential informatio) ofthe servlet (gnerated via the ‘hbtette, werzdi “pakeques® URI= /hello/sayneLloep> “pokenote Address: 127.0.0.20/9> “pon tandem hunters (Skip Unters...) The lke errors are 404 File Not Founc” and “S00 internal Server Error, Read "How to debug” Seton 2.7. STEP 7: Write a Database Servlet ‘This section assumes that you are familar th “lava database programming’ and "MySQL database server Others, rend “ha Databrse Progr owt install MySQL 5 and Get State Step 7(a) Setup a Database on MySQL Start your MySQL sewer Take note ofthe server's port number. shal esume tha ‘on port 9999). he MySQL serve sunning on port 8888 (whereas the Tomcat running 1 or Windows > ed \nyorosece\nsal\in > aysqld console 11 Fon ta $ cd /usr/Local/aysa/oin 5 Sudo s/nyseld safe --consele Starts MySQL dient. Isha sume that there is a user called “nyuser th password “xe” wut ecu 9 homelehchualprogranringibowd/Toreat HowToind si nis. How to Install Tomeat 7 (on Windows, Mac and Ubunty) and Got Started with Java Seret Prograrming 11 Foe Windows > ed \eypragect\nys nin 4 ed fusr/toeal/aysgh/atn 5 cdmyaal -a mjurer “p fu the following SQL statements to cate s database clled"ebookshop” with a table called “books” with columns: Sg, title, author price, aty coeate database 1f not exists ebookshon: create table books Sete varchar(s8), Iuthor varenarts8), prinary key (1d)5 Step 7(b) Install MySQL JDBC Driver ‘You need te download MySQL JDBC diver ify (For Advanced Users Only) You could also place the MySQL driver a-fle "ny Step 7(c) Write a Client-side HTML Form ava for dunes, "Tan Ah Teck’, 34.42, 28); ‘an feck’, 22.22, 23); nonaraad ALS", "38.38, 29); ‘A cop of 3908", Ronan, 58.55, $3)3 ‘A Teaspoon of Java", "Kevin Jones", 65.65, 66); have not done so Read “naling the MySQL. OBC D:ner s-connector-Java-$.1. (+x) Joe" in Tomeat's 14 Lets te an HTML script to create query form with 3 checkboxes and a submit button as stated below, Save the HTML fe as “querybook.htal” Your span ot doy “TOMCAT HOMES webapps\helo One More Bookshop Choose an author: 3 einem You can bromse the HTML page by issuing the following URL: nttps//Lacelhost999/elo/querybook. tal ‘Check box (eg, “Tan Ah Teck’) and dick the “Seareh* button, An HTTP GE ‘Observe the URL ofthe HTTP GET request: netpe//localhort:9999/neLLo/querytathorsTaneAtsTeck ‘The request consists of two pata URL corespanding tothe ‘act on" attibute ofthe
tag, andthe nam ‘ag separated by 9"? Take nate that Blanks ae replaced by "+" (or 32), because blanks ate not allowed inthe URL uur. ecu 9 homelehchualprogranrringibowd/Toreat HowToind ‘Kumar (Search request wil be issued to the URL specie in the 8 onder by price dete"; fut-prinein(“.-- for exch record ‘utiprintin("cpo" + rect getsteing(Tavthor") Oo, te naet getstring("estle") 18; $e rsetegetDouble(*price") + "

"; > ut.printin(“epoeeee * s count + * records found Drintin(-")s sah (SQuEaception ex) { er-pranestackirace(); éinalty ¢ cout.close():// Close the output weiter 11 Step 5: Close the resources 44 (seme I= null) stme-elose()s 1 (Eonn I= mall) cometose(); ) teh (seLEception x) { cx-pranestackirace() Compile the source "QueryServiet. java" hto "QueryServiet class Step 7(e) Configure the Request URL for the Servlet open the confguraton fle "web.xml" of your application "hello" that you have crested earler for the wart. ecu 9 homelehchualprogranringibowd/Toreat HowToind Helloserviet, sai ns. How to Install Tomeat 7 (on Windows, Mac and Ubunty) and Got Started with Java Seret Programming ‘ webapps \helLO\HEB-INF eh. x8)" Add the ne that ae shown in rad at the LOCATIONS INDICATED, 1 cen version".2° encading="I50-8859-1°79 2 cab-app vorsion3.0" 3 omns"Ret: (aver sun.con/aml/ns/3ava0e” 4 andneixet-tnetpi/ wn. org/2001/20Schana-Lnstance 5 tchenatocation="hetp://Jova.sun-con/enl/ts/Javace Metp/Jav.sun.con/sm/ns/ eves ab-ape 9 8.984°> we ‘eervlet-naveet Lorde a “corvlet-rlnerstelioservlote/senvletelass> 2 Yseriet % “serulet-navesUrerguerye/srvlet-nane> 6 ‘Serviet-class>Queryservletc/serviet-lass> DP dsevie B “rervletenaresseLoord/servlet-nane> u ‘ark-pattert/saynelloc/uri-aattern> 25 esenviet-mplg> By ‘Serviet-naweuserqurys/serviet-nane> Fy fart-patters/querycfuni-pattern> 3a cjservlet-nspng® Beye ‘The above lines configure the following URL to invoke QueryServiet: eto: //localhest:9900/neLLo/query Step 7(f) Invoke the Servlet Jssue the follwing URL to browse the HMTL form “querybook. html” that you have crested eal: om the Client-Side Form to: //Localhest9808/nel10/querybook. tnd ‘Select an author fe, "Ton Ah Teck’ and dick the submit button, which states the felling URL coded in the \wesoppe helo \NEB-INF\ clasts Another eServiet 333 2 ingore jevasto.*; 3 port jevaxservtet. sy 4 import Jovae-serviet-netp.t: 5) import Javan servet. annotation. 7 avchsorvaet("/sayht") 4 public class AnotherteLLoservit extends MetpServiet ( 38 T goverride 1e public void doset(Heepservietnequest request, HetpServlethessonse response) a ‘rows ZOexception, servietbeception { a 11 Sot the response MIME ‘ype “ response-setcontent ype "txt jeharset-UIF-8"); uur ecu 9 homelehchualprogranringibowd/Toreat HowTotind si8 ns. How to Install Tomeat 7 (on Windows, Mac and Ubunty) and Got Started with Java Seret Programming as 11 Autncate 2 output writer to write the response nessige Unto the nebvork socket ie Printarster out = response getinter(); s wy ae ‘ou.printin(“ehtaly"); a ‘ut printin("ehend>"); (says Wee 3B ‘ut.printin(" 2 futiprinein("eppPatnireo: * + Feauest-get9arnrneet) + "/B>")i a fut printin(“epotenate Aadresss” + request.getRenotatdde() + "/p3")3 23 17) Generate 3 radon nen upon each renues® 3 ‘outprinein("® + Math.randon() + “e/strong>c/9s" 2 fut prirein("e/bodyperntal>"Y 2 Finally ¢ 2 ‘ut.close()5_ // Alsays clore the output setter » ? BD uM > In Line 7, the annotation ghebserviet(*/sayhi) i used to decive the URL mapping for this servlet, Le, Mt tp://Localhost:9899/helo/ say There is noneed to provide any more confguraton in "web. xe" 3. How to Debug? “Everything that can possibly go wrong willgo wrong” The most important thing todo eto fnd the ERROR MESSAGE! Always. 1, Refresh your browser ving Emt-F5 Gnstend of rereh button or simply FS) to get fresh coy, nse of rom the cache 2. Youmay re-start your Temeat sever You may abo restart your browse o dea the ache 3. Check your speling! Always assume that ll programs are case-sensitive. Dont ype, copy and past if possible 4, and MOST IMPORTANTLY - Find the ERROR MESSAGE! 1. Check the Error Messages on Tomcat Console Mast ofthe eror messages have» few screens of ines. You need to scrall up slow fom the lst line to look forthe FIRST LINE ofthe error messages. Check the Tomcat’ fg fis, locate at "\ Logs", The “catalina. yyyy-mn-d, log" shows the Tomcats startup messages Alko check the “localhost. yyyy-nn-dd. 10g" 5. things were running fre ntl the Ightning strikes, ask yourself "What have I changed?” Cannot Start Tomcat - Tomcat's Console Flashes and Disappears 1. Try runing the script “conFigtest. bat” or Windows) or". /configtest. sh” (or Mac/inue to check your configuration fle 2, Check the Tomes’ logfiles for eror messages. The log fies are leate at “\Logs” The “catalina. (yyyy-amdd) og” shows the Temeat's startup messages Abo check the "Localhost.{y9yy- amd}. Log” 3. Ifthe eror messages inate that another Tomeat instance running Java.net.BindException: Address already in use: 2WM_Bind) kil the Temest process (se bel) oF try running the shutdown’ spt at Tomeats bin For Windows, simply double-cldk the “shutdown bat of sue “snutdoun” fom CMD. For Mac. issue”. /stutdown. sh from Terminal] 4. Ifthe err messages indicate thal another appeaton i running the Temeat's port numbers, then you need to change the Tomes pert number sever. xml. You can stue command netstat an" to check the satu ofl the ports. 5, Stat the tomcat inthe debugging made by running "catalina debug" for -/eatalina.sh debug) and typ run" inthe "Jab" prompt. Look fr the ror messages Locating/Killing Tomeat’s Process = in windows, tet Task Manager Tomes run a 9 process” named “Java. exe”, You may need to kilthe process. «fm Mac stant “Actvty Meriter Sle "Al Processes" and lok for "java.exe" In Lina Mc you may save ps aux | grep toncat to locate the Tomeat process. Note down the proces 1D (pi). You cn kil the Tomeat proces via "ill -9 pid (Firefox) Unable to Connect (JE) Internet Explorer cannot display the webpage (Chrome) Oops! Google Chrome could nat connect to (Safari) Safari can't connect to the server Cause: Vou ae sinply not connecting o your Tomeat wart. ecu 9 homelehchualprogranringibowd/Toreat HowToind wis. ns. How to Install Tomeat 7 (on Windows, Mac and Ubunty) and Got Started with Java Seret Programming Sekt 1. Checkif your Tomcat server hasbeen started? 2. Check the hostname and port number, separated bya colon ':",ofyour URL (nttp:// localhost :9999/...) Error 404 File Not Found “Cause You have connected to your Tomest But Toma server cannot find the HTMI fle or Servet that your requested Seton 1. Check your spaling! The path is ese-sostive 2, For HTML fe with URL tp: //Lcathos:9999/xax0/fiLenane neal 5. Open Tomeats webapps" decry, check if sub-deecory era’ exts. I case-senstive, . Open the sex’ crectory, check ff Lenawe htm” ests 3. For Servlet with URL ntty://Laeathost: 9999/14 serv etURL ‘Check the Tama’ consol freer message: Your appleation cannot be deployed f you make a mistake In eng ‘web. xnl” which tiggead many eror messages. b. Check the Tomeat console to make sure that your appletion hasbeen deployed. Open Tomeat's webapps" drectory, cack f sub-directory "oe ext. 44 Open the een retary, check Wf sub-sub-dretory WEB-INE (uppercase with a dash) ests ©, Open the WEB-INF check #sub-sub-sub drectory “esses” fowercase, pur) ess. (pen the configuration fle WEB-INF\web x0" 1: Check that servLetURE iden in a cserviet-mapping> tag. Tae no of the ane in tag, 1b, Based on the name noted, look forthe matching tag Take note ofthe ServletCLassnane, © Open 'WEB-INF\classes’ check i'ServLetCLassname.classé that you noted exists (Notes. €Lass" and NOT. java’. You noes to comple the "java to get the” class") Error S00 Internal Server Error Error 500 should have triggered many error message inthe Tomeats console. Go to the Tomeats console find the errr message, The etror message Spans tens of Ines, You need to <0 up slowly to ok forthe fest line ofthe error message. The error message shou tll you the cuage ofthis errr, €g, SQL syntax ero, wrong ustfpasmord ete For database seret, you may check the error messages at "Common Ear in JDBC Programming 1 For "No stable diver found” Windows) or NulTPointerException (Mac and Linu Read Step 7(b again. again and agin More Errors Try Searching ‘Common tor Messages REFERENCES & RESOURCES 1. Apache Tomeat mathar ste @ hnp/itomestapscie ors 2. Apache Tomest Documentation ® " \webapps\ docs’ 3. “How to install MySQL and Get Started 4, “Inodicion to Jv Database UOBC) Programming 5. Jason Bein, an F-Daewin, “Tomcat The Definitive Guide, 2nd eds, ORely, 2007, lest moatios: September, 2013, Feedback, comments, cations, ana eta can be sent to Chua Hoek-Chwan fehehuaentvedsa) | wurtu.ecu 9 homelehchualprogranringibowd/Toreat Howard asi

You might also like