计算机专业文献翻译用 Tomcat 和 Eclipse开发 Web 应用程序.docx
《计算机专业文献翻译用 Tomcat 和 Eclipse开发 Web 应用程序.docx》由会员分享,可在线阅读,更多相关《计算机专业文献翻译用 Tomcat 和 Eclipse开发 Web 应用程序.docx(20页珍藏版)》请在冰豆网上搜索。
计算机专业文献翻译用Tomcat和Eclipse开发Web应用程序
DevelopingWebapplicationswithTomcatandEclipse
Requiredcomponents
TheEclipseV3.2Callistointegrateddevelopmentenvironment(IDE)includestoolsfordoingWebdevelopmentandintegratingwithservers.So,asidefromthesoftwaredevelopmentkit(SDK),youneedonlyEclipseandApacheTomcatinstalled.Theversionsfeaturedinthisarticlearelistedbelow.
Table1.Componentsandversionsused
Component
Versionusedinthisarticle
EclipsePlatform
3.2.2
JavaEE5SDK
1.5.0_09
ApacheTomcat
5.5.20
TheEclipseIDEisanopensourceIDEusedasthedevelopmentenvironmentforyourJava™ServerPages(JSPs)andJavafiles.WiththeWebandJava2Platform,EnterpriseEdition(J2EE)Developmenttoolsinstalled,EclipseisgreattoolforcreatingHTML,JSPs,andservlets.
YouneedtheJavaSDKtorunservletsonyourmachine.Finally,ApacheTomcatisanopensourceWebandservletcontainer,usedintheofficialreferenceimplementationsforJavaServletandJavaServerPages.
Installation
InstallationofEclipseandTomcatissimilar—bothareextractedfromthearchivefileformatintoafolderonyourharddisk.Ifyoueverwanttouninstalleither,it'sassimpleasdeletingthedirectoryinwhichyouextractedthefiles.
InstallEclipse
ToinstalltheEclipseIDE,unpackthecompressed(.zipor.tar.gz)fileyoudownloadedfromEclipse,thenmovetheunpackedfolderintoaconvenientlocation.ItrytoinstallitinalocationthatfollowstheconventionsofwhateveroperatingsystemI'musing.IfI'minstallingEclipseonaMacintosh,IputtheEclipsefolderintheApplicationsfolder.IfI'musingMicrosoft™Windows™,IputtheunpackedfolderintotheC:
\ProgramFilesdirectory.
Onceyou'vedownloadedandinstalledEclipse,startitup.BeforeyoucancreateaWebproject,youneedtoinstalltheJ2EEandWebDevelopmentplug-ins.Fortunately,it'seasytoinstalltheplug-inusingtheCallistoDiscoverySite.
InstalltheWebtools
WiththeEclipseIDErunning,selectHelp>SoftwareUpdates>FindandInstall.ThisoptionletsyoudownloadandinstalltheWebtoolswithoutgoingtoaWebsite.
SelectSearchforNewFeaturestoInstall,asshownbelow,thenclickNext.
Figure1.Install/Updatewindow
SelectCallistoDiscoverySite,asshownbelow,thenclickNext.
Figure2.SelecttheCallistoDiscoverySite
UnderCallistoDiscoverySite,checktheWebandJ2EEDevelopmentbox.Thewizardimmediatelywarnsyouthatyou'remissingdependencies.ClickSelectRequired,andthesewarningsshoulddisappear.SomeorallofthecomponentsintheGraphicalEditorsandFrameworksandModelsandModelDevelopmentcategoriesareselected(asshowninFigure3)becausethey'rerequiredfortheinstallationoftheWebandJ2EEplug-ins.
Figure3.Selectfeaturesforinstallation
ClickNexttocontinue,andlicenseagreementsappearforeachfeatureyou'veselected.Ifyouagreewiththelicenses,acceptthemandfollowthewizardthroughtherestoftheprocess.WhentheIDEisfinishedinstallingtheplug-ins,itasksyoutorestartEclipseinorderforthechangestotakeeffect.BesureyourestarttheIDEbeforecontinuing.
AfteryourestarttheIDE,thenewfeaturesareavailabletobegindevelopingdynamicWebprojects.
InstallTomcat
ToinstallApacheTomcat,extractthefilesfromthedownloadedarchiveandplacethemintoadirectory.IputtheminmyC:
\appsdirectorytomakethemeasytolocatelater.That'sitfornow;useEclipseasshownlatertostartTomcat.
CreateanewWebproject
FromtheEclipseIDE,selectFile>New>Projecttoviewtheprojectwizards.TypeWebintheWizardsbox,andtheNewProjectwindowfiltersthewizardstoshowtheonesthatmatch.Thisisaneasywaytolocatethewizardyouwantinsteadofgoingthrougheachitem.
ChooseDynamicWebProjectfromthelist.YouusetheStandardWebProjectWizardtomakestaticHTMLWebprojects.YoucantechnicallyuseTomcattorunstaticWebsites,althoughaWebserversuchasApacheWebServermaybeabetterchoiceforstaticcontent.Webserversbuiltspecificallyforservingupstaticpagestendtohavelessoverheadandaretunedforthatpurpose.
Targetaruntime
UnderTargetRuntime,yousee,asshowninFigure4,becauseyouhaven'tcreatedaruntimeyetforApacheTomcat.ClickNewtoopentheNewTargetRuntimeWizard.SelectApacheTomcatV5.5fromtheApachefolder,asshowninFigure5,thenclickNext.
Figure4.CreateanewdynamicWebproject
Figure5.Createanewserverruntime
Nowyouhavetheopportunitytonameyourruntime,althoughthedefaultnameApacheTomcatV5.5isfine.ClickBrowsetolocatethebasefolderforyourApacheTomcatconfiguration(mineisC:
\apps\apache-tomcat-5.5.20,asshowninFigure6).IrecommendleavingtheIBM®JavaRuntimeEnvironment(JRE)versionthesameastheworkbenchdefaultJRE,unlessyouhaveaspecificreasontochangeit.Onceyou'veenteredavaliddirectory,clickFinishtocreatetheruntimeconfiguration.
Figure6.Definetheserverlocation
You'reaskedifyouwanttoswitchtotheJ2EEPerspective.IalwaysansweryesbecausethatperspectiveincludesviewsliketheServersview,whichhelptostartandstopTomcatlater.YoucanalwaysopentheServersviewbyselectingWindow>ShowView.
Addtheserver
IntheServersviewisaviewthatcontainsnothing.ThisviewisforapplicationandWebservers;itletsyoucontrolthemandmonitortheirstatus.TocontrolTomcatdirectlyfromthecomfortoftheIDE,addareferencetoTomcatbyselectingNew>Serverfromthecontext-sensitivemenu.TheNewServerwizard,asshowninFigure7,willdefaulttotheApacheTomcatV5.5runtimeyoujustcreated.
Figure7.Defineanewserver
ClickNext.You'reaskedwhetheryouwanttoaddprojectstotheserver.Selecttheprojectyoucreatedintheprevioussteps,thenclickAdd.
Figure8.Addtheprojectstotheserver
ClickFinishtoclosethewizard.NowtheServersviewcontainstheTomcatV5.5Serverwiththeprojectunderit.
Figure9.TheTomcatserverintheServersview
Createasamplepage
TheeasiestwaytotestyournewdynamicWebprojectandTomcatserverintegrationistocreateasimpleJSPanddeployittoTomcat.YoucancreatethenewJSPfilebyselectingFile>New>Other,oryoucanusethecontext-sensitivemenubyright-clickingtheprojectnameintheProjectExplorerviewandselectingNew>JSP.
MakesuretheparentfolderisWebContentandnamethefileindex.jsp.ClickFinishtocreatethepageusingthedefaulttemplate.IfyouclickNext,youcanchoosedifferenttemplatestouse(suchasHTMLorXHTML)forthenewpage.Thedefaultsarefineforthistest.
Thepagecodeshownbelowdisplaysasimpledatesoyoucanseeitworking.
Listing1.Contentsofindex.jsp
<%@pagelanguage="java"contentType="text/html;charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"
"http:
//www.w3.org/TR/html4/loose.dtd">
MyTitle<%java.util.Dated=newjava.util.Date();%>
Today'sdateis<%=d.toString()%>andthisjsppageworked!
Deploythepage
Nowthatthetestpageiscomplete,useEclipsetoredeployittoApacheTomcat.IntheServersview,noticethatStateissettoRepublish.Thatisbecausechangeshavebeenmadesincetheprojectwaslastdeployedtotheserver.Right-clicktheserverandselectPublishfromthemenu.ThestatechangestoSynchronizedoncetheprojecthasbeendeployedtotheserver.
Withtheprojectsuccessfullydeployedandtheserverstarted,openabrowserandnavigatetohttp:
//localhost:
8080/[ProjectName]/(where[ProjectName]isthenameofthedynamicWebprojectyoucreated).ThenewWebpageyoucreatedappears,andthedateshouldbecurrent.Ifyourefreshthepage,thedatechanges.
Figure10.Outputofindex.jspinabrowser
HelloWorldservlet
YoucanaddJavaservletstoyourprojectanddeploythem.Tocreateaquickservletyoucanusefortestingpurposes,usetheServletWizardbyright-clickingyourdynamicWebprojectintheProjectExplorerviewandselectingNew>Other.UndertheWebfolder,selectServlet,thenclickNext.
Addthepackagenamecom.example.servletsnexttoJavaPackageandaddHelloServletnexttoClassname.ClickFinish.Thisisanexample,sothedefaultsarefine.TheEclipseIDEgeneratesaservletclassforyou.Towatchthetestservletinaction,addalineinthedoGet()methodtoprintamessagetotheResponseWriter.Theservletclassshouldlookliketheoneshownbelow.
Listing2.ContentsofHelloServlet.java
packagecom.example.servlets;
importjava.io.IOException;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
/**
*ServletimplementationclassforServlet:
HelloServlet
*
*/
publicclassHelloServletextendsjavax.servlet.http.HttpServlet
implementsjavax.servlet.Servlet{
/*(non-Java-doc)
*@seejavax.servlet.http.HttpServlet#HttpServlet()
*/
publicHelloServlet(){
super();
}
/*(non-Java-doc)
*@seejavax.servlet.http.HttpServlet#doGet(HttpServletRequestrequest,
HttpServletResponseresponse)
*/
protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
response.getWriter().write("Hello,world!
");
}
/*(non-Java-doc)
*@seejavax.servlet.http.HttpServlet#doPost(HttpServletRequestrequest,
HttpServletResponseresponse)
*/
protectedvoiddoPost(HttpServletRequestrequest,HttpS