Struts Tutorial Passo A Passo 阳飞.docx
《Struts Tutorial Passo A Passo 阳飞.docx》由会员分享,可在线阅读,更多相关《Struts Tutorial Passo A Passo 阳飞.docx(52页珍藏版)》请在冰豆网上搜索。
StrutsTutorialPassoAPasso阳飞
StrutsTutorial
Authors:
StephanWiesner(stephan@stephanwiesner.de)
Version:
1.03
MajorchangeoftheunderlyingXMLstructure(footnotes,glossary,directoryoflistings,etc)
ChapteraboutTemplates.
UsingANTforcreationofWARfiles.
(English)
Published:
14.04.2002
Abstract
ThisisatutorialfortheStrutsframework.Itconsistsofasmallapplicationwhichisdevelopedstepbystep.Bookscanbedisplayedinthebrowser,newbookscanbecreatedandtheirstatesaved/loadedinxmlfiles.Itrytodothewholethingstepbystep,withlotsofscreenshotstoshowthatitreallydoesworkandtohelpyoualong.Manyofthescreenshotsactuallyshowerrormessages.Thiswillhelpyouavoidsomeofthemanypitfallsalongtheway.ThisworkshouldenableyoutoworkwithStrutsinashorttime,butyouwillnotbecomeaStrutsguruwithit.So,youshouldhavetheofficialdocumentationathandtoreadthetheoreticalbackground.
Contents:
I.Introduction
II.InstallationofStruts
III.TheFirstTry:
SimpleJSP
IV.SecondTry:
StrutsForInternationalization
V.StrutsforForms
VI.Struts:
IntroducingtheActionForm
VII.AbetterwaytoseparateBookandBookForm
VIII.HandlingInvalidEntries
IX.Recapitulation:
Whereweare
X.UsingLogic
XI.Templates
XII.FAQ
XIII.BeanstoXML
XIV.ReplacingJSPwithXSLT
XV.IntroducingAspectJ
XVI.AntforCompilationandDistribution
XVII.Conclusions
XVIII.Epilogue:
TechnicalBackgroundaboutthisDocument
XIX.AbouttheAuthor
1.Introduction
WhyIwrotethetutorial,whoisthetargetgroupandanoverviewofthecontents.
Goals:
Togetanideawhatthistutorialisaboutandwhetheryoushouldbeabletolearnsomethingnew.
DuringthistutorialIwilldevelopalittleapplication,stepbystep,thatimplementsApacheStruts.
YoushouldhavesomeexperiencewithJavaServerpages,JSPandXML.Furtheryoushouldhaveaserverimplementedthatcanrunthosethings.Seemyhomepageforatutorialaboutthat,ifnot.
ThetutorialwillstartwiththeinstallationoftheStrutsframeworkitself,willimplementsomeminimalisticfeaturesinpureHTMLandwillthenaddsomeStrutsfuntionality,givinghintsandthoughtsabouthowtoorganizeyourcode.FinallyI'llevenshowyousometrickswithAspectJtomakeyourlifeasaprogrammersomewhateasier.
Thistutorialisunderconstantdevelopment,socheckbackfromtimetotime.Alsotakealookatthechapterabouttechnicalbackgrounds.Itmightinterestyou.
2.InstallationofStruts
Thisoneisquiteeasy.Itakeit,youhavearunningTomcat3.2(orcomparableserver)andknowhowtohandleit?
Illustration1:
Thefolderstructure
1.Generateadirectorystructurelikeinthescreenshot(adaptifyoudon'tuseTomcat)
2.Downloadthenewest(binary)versionofStruts(IUse1.0.2)[I].
3.Extractthedownload.
4.CopytheStruts.jar
5.Pasteittothelibdirectoryofyourapplication(seeabove).DON'T,IrepeatDON'TjustaddittoyourCLASSPATH!
Ididthatanditworkedfine.UntilIrestartettheTomcat,thatis.Tookmequiteawhiletofiguretheconnectionout.Atleastwithmysystemtherewasabigproblem,soIrecommendtoadditjusttothisapplication.
6.Thatisall,forthemoment.Don'tdeletetherestoftheStrutsdownload,though.Wewillneedmorelateron.
3.TheFirstTry:
SimpleJSP
WewillstartwithasimpleJSPpage,justtoensurethatwedideverythingrightuntilnow.CreateafilecalledBookView.jspinthe'strutsShop'-directory.
FirstJSP
<%@pagelanguage="java"%>
StrutsTutorial:BookView
BookView
html>
Illustration2:
OurFirstPage
Notveryimpressive,Iadmit,butwewillstartimprovingitrightaway.
4.SecondTry:
StrutsForInternationalisation
WewilluseStrutstodisplaypredefinedtextsinthedefaultlanguageoftheuser.Well,notforeveryuser,Isuppose...ThiswillrequiresomecloserlookatthefunctionalityofStruts.
Goals:
Displaythetitleofthepageindifferentlanguages.
WestartswithsomebasicsaboutStruts:
GotothedirectoryyouextractedtheStrutsdownloadtoandcopysomefilestoourWEB-INFdirectorylikeinthescreenshot(youshouldbrowsethroughafewoftheexamplesthatcomewithStruts,whilesearchingforthem).
Illustration3:
NeededLTDfiles
Takethetimetolookintothestruts-html.tldfile.Don'tpanic,though,wewillnotadaptthosefiles!
TheyaretheretohelpusanddefinethefunctionalityofStruts.YoucanfindtheparametersyouneedforusingaStruttaginthere.Youcouldlookintotheofficialdocuandwouldprobablybebetteroff,though.
Ourweb.xmlmustdefineanactionServletandthelinkstotheltd-files.Justcopyoneweb.xmlfromtheStrutssourcesandremoveeverythingelse.
EmptyStruts-config.xml
xmlversion="1.0"encoding="ISO-8859-1"?
>
DOCTYPEstruts-configPUBLIC
"-//ApacheSoftwareFoundation//DTDStrutsConfiguration1.0//EN"
"http:
//jakarta.apache.org/struts/dtds/struts-config_1_0.dtd">
web.xml
xmlversion="1.0"encoding="ISO-8859-1"?
>
DOCTYPEweb-app
PUBLIC"-//SunMicrosystems,Inc.//DTDWebApplication2.2//EN"
"
action
org.apache.struts.action.ActionServlet
application
ApplicationResources
config
/WEB-INF/struts-config.xml
debug
2
detail
2
validate
true
2
--StandardActionServletMapping-->
action
*.do
--TheWelcomeFileList-->
index.jsp
index.html
--StrutsTagLibraryDescriptor-->
/WEB-INF/struts-bean.tld
/WEB-INF/struts-bean.tld
/WEB-INF/struts-html.tld
/WEB-INF/struts-html.tld
/WEB-INF/struts-logic.tld
/WEB-INF/struts-logic.tld
/WEB-INF/struts-template.tld
/WEB-INF/struts-template.tld
Okay,letsstartwithsomethingreallyeasy.Wewilldisplaythetitleofthepageindifferentlanguages,dependingonthepreferenceoftheuser.
Createafilecalled'ApplicationResources.properties'intheclassesdirctory.
Openitandentertheline:
'index.title=StrutsTutorial'intoit
Createanotherfilecalled'ApplicationResources_de.properties'(deforDeutschland(germany))andenter'index.title=StrutsEinführung'
EdittheBookView.jspandchangetheheadto:
BookView.jsp:
IntroducingInternationalization
<%@pagelanguage="java"%>
<%@tagliburi="/WEB-INF/struts-bean.tld"prefix="bean"%>
<%@tagliburi="/WEB-INF/struts-html.tld"prefix="html"%>
<%@tagliburi="/WEB-INF/struts-logic.tld"prefix="logic"%>
htmllocale="true">
base/>
messagekey="index.title"/>
Illustration4:
Displayingthegermantitleelement
NowyouhavetorestartyourTomcatandafterreloadingthepageyoushouldseeatitle.Whatexactlyyouseedependsonthedefaultlanguageonyourcoumputer.Iseethegermantitle'StrutsEinführung'.Changeyourdefaultlanguageandrelaodthepage.Setitfirsttoenglish,thentogermanandthetitleshouldadaptaccordingly.
Note:
Asyoujustsawitisveryeasytodisplaytextsindifferentlanguages.Whatyouwillrealizeveryquickly,though,ishowtediousitcangettoenter/check/changeeverythingindifferentlanguages,butthathasnothingtodowiththewayitisimplementedinStruts.IhavemadetheexperiencethatitisamusttoimplementeveryTextusingthevariablesandthatitisbesttousejustonefileforthedevelopment.then,beforemakingarelease,Iadaptthefilesfortheotherlanguages.ThiswayIsavealotoftime.Don'tthinkyoucanwriteplaintextandexchangeitforvariablesatreleasetimethough!
5.StrutsforForms
Thischapterwillfinallyallowustodosomerealprogramming(abouttime,Iknow).WewillcreateasimpleBean(Book.java)andtwoJSPpages.Onetocreateanewbookandasecondtodisplayit.ForthatwewilluseStruts.Further,wewilltakeafirstlookatthestruts-config.xmltoconfigureourapplication.
Goals:
TounderstandhowStrutscanhelpuswithstandardbehaviourconcerningforms.
Let'sstartwiththeBean.CreateafileBook.java[II]inyourclassesdirectoryandenterthefollowing:
Book.java
importjava.util.Vector;
/*
Asimplebook.
@authorstephan@stephanwiesner.de
*/
publicclassBook
{
/**Thetitle*/
privateStringtitle="";
/**Wecanhavemorethanoneauthor*/
privateVectorauthors=newVector();
/**Thenumberofpagesthebookhas*/
privateintpages=0;
/**Standardconstructor.*/
publicBook()
{}
/**@paramtitleThenewTitle*/
publicvoidsetTitle(Stringtitle)
{this.title=t