introduction to the struts web framework - netbeans ide tutorial

Post on 18-Dec-2015

9 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

tip

TRANSCRIPT

  • 14/4/2015 IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial

    https://netbeans.org/kb/docs/web/quickstartwebappsstruts.html 1/14

    NetBeansIDE NetBeansPlatform Enterprise Plugins Docs&Support Community Search

    HOME/Docs&Support

    IntroductiontotheStrutsWebFrameworkThisdocumenttakesyouthroughthebasicsofusingNetBeansIDEtodevelopwebapplicationsusingtheStrutswebframework.StrutsisanopensourceframeworkthatextendstheJavaServletAPIandemploysaModel,View,Controller(MVC)architecture.Itenablesyoutocreatemaintainable,extensible,andflexiblewebapplicationsbasedonstandardtechnologies,suchasJSPpages,JavaBeans,resourcebundles,andXML.

    ThistutorialteachesyouhowtobuildasimpleMVCapplicationthatdisplaysaloginpageandreturnsasuccesspageuponsubmittingdatathatpassesvalidation.YoulearnseveralbasicfeaturesprovidedbyStruts,aswellashowthesefeaturesareimplementedusingtheIDE.Specifically,youuseStrutstagsinJSPpages,maintainuserdatawithaStrutsActionFormbean,andimplementforwardinglogicusingaStrutsActionobject.Youarealsoshownhowtoimplementsimplevalidationtoyourapplication,includingsettingupwarningmessageforafailedloginattempt.

    ForamorefinegrainedintroductiontoStruts,seeHowdoesStrutswork?ontheofficialStrutswebsite.Also,makeuseoftheIDE'sJavadocIndexSearch(Help>JavadocIndexSearch)toviewtheStrutsFrameworkAPI,whichispackagedwiththeStrutslibraries.

    Contents

    OverviewoftheApplication

    SettingUpaStrutsApplication

    CreatingJSPPages

    CreatingaLoginPage

    CreatingaSuccessPage

    CreatinganActionFormBean

    CreatinganActionClass

    ImplementingValidation

    AccessingBeanDataandPreparingaForwardingCondition

    SettingUpanErrorMessage

    AddingforwardEntriestostrutsconfig.xml

    ConfiguringandRunningtheApplication

    SettingtheWelcomePage

    AttachingaStylesheet

    RunningtheApplication

    SeeAlso

    Tocompletethistutorial,youneedthefollowingsoftwareandresources.

    SoftwareorResource VersionRequired

    NetBeansIDE 7.2,7.3,7.4,8.0,JavaEE

    JavaDevelopmentKit(JDK) 7or8

    GlassFishserveror

    Tomcatservletcontainer

    OpenSourceEdition3.xor4.0

    version7.xor8.x

    Notes:

    TheJavainstallationenablesyoutooptionallyinstalltheGlassFishserverandtheApacheTomcatservletcontainer.Youmustinstalloneofthese(orregisteradifferentserverintheIDE)toworkthroughthistutorial.

    Ifyouneedtocompareyourprojectwithaworkingsolution,youcandownloadthesampleapplication.

    OverviewoftheApplicationWhenyouuseStruts,theframeworkprovidesyouwithacontrollerservlet,ActionServlet,whichisdefinedintheStrutslibrariesthatareincludedintheIDE,andwhichisautomaticallyregisteredintheweb.xmldeploymentdescriptorasshownbelow.Thecontrollerservletusesastrutsconfig.xmlfiletomapincomingrequeststoStrutsActionobjects,andinstantiateanyActionFormobjectsassociatedwiththeactiontotemporarilystoreformdata.TheActionobjectprocessesrequestsusingitsexecutemethod,whilemakinguseofanydatastoredintheformbean.OncetheActionobjectprocessesarequest,itstoresanynewdata(i.e.,intheformbean,orinaseparateresultbean),andforwardstheresultstotheappropriateview.

    Training

    JavaProgrammingLanguage

    Support

    OracleDevelopmentToolsSupportOfferingforNetBeansIDE

    DocumentationGeneralJavaDevelopmentExternalToolsandServicesJavaGUIApplicationsJavaEE&JavaWebDevelopmentWebServicesApplicationsNetBeansPlatform(RCP)andModuleDevelopmentPHPandHTML5ApplicationsC/C++ApplicationsMobileApplications

    SampleApplicationsDemosandScreencasts

    MoreFAQsContributeDocumentation!DocsforEarlierReleases

    Choosepagelanguage

  • 14/4/2015 IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial

    https://netbeans.org/kb/docs/web/quickstartwebappsstruts.html 2/14

    DevelopingaStrutsapplicationissimilartodevelopinganyotherkindofwebapplicationinNetBeansIDE.However,youcomplementyourwebdevelopmenttoolkitbytakingadvantageoftheStrutssupportprovidedbytheIDE.Forexample,youusetemplatesintheIDEtocreateStrutsActionobjectsandActionFormbeans.Uponcreation,theIDEautomaticallyregisterstheseclassesinthestrutsconfig.xmlfileandletsyouextendthisfileveryeasilyusingmenuitemsintheSourceEditor'srightclickmenu.BecausemanywebapplicationsuseJSPpagesfortheview,StrutsalsoprovidescustomtaglibrarieswhichfacilitateinteractionwithHTMLforms.WithintheIDE'sSourceEditor,youcaninvokecodecompletionandJavadocsupportthathelpsyoutoworkefficientlywiththeselibraries.

    Thefollowingstepsdemonstratehowtocreateasimpleformthatcollectsuserdata,performssimplevalidation,andoutputsthedataonasuccesspage.

    SettingUpaStrutsApplicationIntheIDE,aStrutsapplicationisnothingmorethananormalwebapplicationaccompaniedbytheStrutslibrariesandconfigurationfiles.YoucreateaStrutsapplicationinthesamewayasyoucreateanyotherwebapplicationintheIDEusingtheNewWebApplicationwizard,withtheadditionalstepofindicatingthatyouwanttheStrutslibrariesandconfigurationfilestobeincludedinyourapplication.

    1. ChooseFile>NewProject(CtrlShiftNShiftNonMac)fromthemainmenu.SelectJavaWebinthelistofCategoriesandthenselectWebApplicationinthelistofProjects.ClickNext.

    2. IntheNameandLocationpanel,enterMyStrutsAppforProjectNameandclickNext.

    3. IntheServerandSettingspanel,selecttheservertowhichyouwanttodeployyourapplication.OnlyserversthatareregisteredwiththeIDEarelisted.(Toregisteraserver,clickAddnexttotheServerdropdownlist.)Also,notethattheContextPathtoyourdeployedapplicationbecomes/MyStrutsApp.ClickNext.

    4. SelectStrutsintheFrameworkspanel.

    Forpurposesofthistutorial,donotchangeanyoftheconfigurationvaluesinthelowerregionofthispanel.Thewizarddisplaysthefollowingconfigurationoptions.

    ActionServletName:ThenameoftheStrutsactionservletusedintheapplication.Theweb.xmldeploymentdescriptor

  • 14/4/2015 IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial

    https://netbeans.org/kb/docs/web/quickstartwebappsstruts.html 3/14

    containsanentryfortheactionservletandspecifiestheappropriateStrutsspecificparameters,suchasthepathtotheservletclasswithintheStrutslibraryandtothestrutsconfig.xmlconfigurationfilewithintheapplication.

    ActionURLPattern:SpecifiesthepatternsofincomingrequestswhicharemappedtotheStrutsactioncontroller.Thisgeneratesamappingentryinthedeploymentdescriptor.Bydefault,onlythe*.dopatternismapped.

    ApplicationResource:Letsyouspecifytheresourcebundlewhichwillbeusedinthestrutsconfig.xmlfileforlocalizingmessages.Bydefault,thisiscom.myapp.struts.ApplicationResource.

    AddStrutsTLDs:LetsyougeneratetaglibrarydescriptorsfortheStrutstaglibraries.AtaglibrarydescriptorisanXMLdocumentwhichcontainsadditionalinformationabouttheentiretaglibraryaswellaseachindividualtag.Ingeneralthisisnotnecessary,becauseyoucanrefertoonlineURIsratherthanlocalTLDfiles.

    5. ClickFinish.TheIDEcreatestheprojectfolderinyourfilesystem.AswithanywebapplicationintheIDE,theprojectfoldercontainsallofyoursourcesandtheIDE'sprojectmetadata,suchastheAntbuildscript.However,yourwebapplicationinadditionhasalloftheStrutslibrariesonitsclasspath.Notonlyaretheyontheapplication'sclasspath,buttheyareincludedintheprojectandwillbepackagedwithitlaterwhenyoubuildtheproject.

    TheprojectopensintheIDE.TheProjectswindowisthemainentrypointtoyourprojectsources.Itshowsalogicalviewofimportantprojectcontents.Forexample,ifyouexpandseveralnodeswithinthenewproject,itmayappearasfollows:

    Note:UsetheFileswindow(Window>Files)toseeallofyourprojectcontentsinadirectorybasedview.

    TheStrutsspecificconfigurationfiles,aswellastheapplication'sdeploymentdescriptor,areconvenientlyplacedwithintheConfigurationFilesfolder.Openthedeploymentdescriptor(doubleclicktheweb.xmlfilenodetohaveitdisplayintheSourceEditor).InordertohandleStrutsprocessing,amappingisprovidedfortheStrutscontrollerservlet.

    action

    org.apache.struts.action.ActionServlet

    config

    /WEBINF/strutsconfig.xml

    debug

    2

  • 14/4/2015 IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial

    https://netbeans.org/kb/docs/web/quickstartwebappsstruts.html 4/14

    detail

    2

    2

    action

    *.do

    Above,theStrutscontrollerservletisnamedactionandisdefinedintheStrutslibrary(org.apache.struts.action.ActionServlet).Itissettohandleallrequeststhatsatisfythe*.domapping.Inaddition,initializationparametersfortheservletarespecifiedbymeansofthestrutsconfig.xmlfile,alsocontainedintheWEBINFfolder.

    CreatingJSPPagesBeginbycreatingtwoJSPpagesfortheapplication.Thefirstdisplaysaform.Thesecondistheviewreturnedwhenloginissuccessful.

    CreatingaLoginPage

    CreatingaSuccessPage

    CreatingaLoginPage

    1. RightclicktheMyStrutsAppprojectnode,chooseNew>JSP,andnamethenewfilelogin.ClickFinish.Thelogin.jspfileopensintheSourceEditor.

    2. IntheSourceEditor,changethecontentofboththeandtags(ortags,dependingontheIDEversionyouareusing)toLoginForm.

    3. Addthefollowingtwotaglibdirectivestothetopofthefile:

    ManywebapplicationsuseJSPpagesforviewsintheMVCparadigm,soStrutsprovidescustomtaglibrarieswhichfacilitateinteractionwithHTMLforms.ThesecanbeeasilyappliedtoaJSPfileusingtheIDE'ssupportforcodecompletion.WhenyoutypeintheSourceEditor,theIDEprovidesyouwithcodecompletionforStrutstags,aswellastheStrutsJavadoc.YoucanalsoinvokecodecompletionmanuallybypressingCtrlSpace:

    Thebeantaglibprovidesyouwithnumeroustagsthatarehelpfulwhenassociatingaformbean(i.e.,anActionFormbean)withthedatacollectedfromtheform.Thehtmltagliboffersaninterfacebetweentheviewandothercomponentsnecessarytoa

  • 14/4/2015 IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial

    https://netbeans.org/kb/docs/web/quickstartwebappsstruts.html 5/14

    webapplication.Forexample,belowyoureplacecommonhtmlformtagswithStruts'tags.Onebenefitthisprovidesisthatitcausestheservertolocateorcreateabeanobjectthatcorrespondstothevalueprovidedforhtml:form'sactionelement.

    4. Belowthe(or)tags,addthefollowing:

    WheneveryoufinishtypingintheSourceEditor,youcantidyupthecodebyrightclickingandchoosingFormat(AltShiftF).

    5. InthePalette(Window>Palette)intherightregionoftheIDE,dragaTableitemfromtheHTMLcategorytoapointjustabovetheline.TheInsertTabledialogboxdisplays.Settherowsto3,columnsto2,andleaveallothersettingsat0.Laterinthetutorial,youwillattachastylesheettoaffectthetabledisplay.

    ClickOK,thenoptionallyreformatthecode(AltShiftF).Theforminlogin.jspnowlooksasfollows:

    Note:Youcansafelydeletethetablerow,asitisnotusedinthistutorial.

    6. Inthefirsttablerow,enterthefollowing(changesinbold):

  • 14/4/2015 IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial

    https://netbeans.org/kb/docs/web/quickstartwebappsstruts.html 6/14

    Enteryourname:

    7. Inthesecondtablerow,enterthefollowing(changesinbold):

    Enteryouremail:

    Thehtml:textelementenablesyoutomatchtheinputfieldsfromtheformwithpropertiesintheformbeanthatwillbecreatedinthenextstep.Soforexample,thevalueofpropertymustmatchafielddeclaredintheformbeanassociatedwiththisform.

    8. Movetheelementintothesecondcolumnofthethirdtablerow,sothatthethirdtablerowappearsasfollows(changesinbold):

    Atthisstage,yourloginformshouldlookasfollows:

    Enteryourname:

    Enteryouremail:

    CreatingaSuccessPage

    1. RightclicktheMyStrutsAppprojectnode,chooseNew>JSP,andnamethenewfilesuccess.IntheFolderfield,clicktheadjacentBrowsebuttonandselectWEBINFfromthedialogthatdisplays.ClickSelectFoldertoenterWEBINFintheFolderfield.AnyfilescontainedintheWEBINFfolderarenotdirectlyaccessibletoclientrequests.Inorderforsuccess.jsptobeproperlydisplayed,itmustcontainprocesseddata.ClickFinish.

    2. IntheSourceEditor,changethecontentofthenewlycreatedpagetothefollowing:

    LoginSuccess

    Congratulations!

    Youhavesuccessfullyloggedin.

    Yournameis:.

    Youremailaddressis:.

    3. Addabeantaglibdirectivetothetopofthefile:

  • 14/4/2015 IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial

    https://netbeans.org/kb/docs/web/quickstartwebappsstruts.html 7/14

    4. Addthefollowingtags(changesinbold):

    Yournameis:.

    Youremailaddressis:.

    Byemployingthetags,youmakeuseofthebeantaglibtolocatetheActionFormbeanyouareabouttocreate,anddisplaytheuserdatasavedfornameandemail.

    CreatinganActionFormBeanAStrutsActionFormbeanisusedtopersistdatabetweenrequests.Forexample,ifausersubmitsaform,thedataistemporarilystoredintheformbeansothatitcaneitherberedisplayedintheformpage(ifthedataisinaninvalidformatorifloginfails)ordisplayedinaloginsuccesspage(ifdatapassesvalidation).

    1. RightclicktheMyStrutsAppprojectnodeandchooseNew>Other.UnderCategorieschooseStruts,thenunderFileTypeschooseStrutsActionFormBean.ClickNext.

    2. TypeinLoginFormfortheClassName.Thenselectcom.myapp.strutsinthePackagedropdownlistandclickFinish.TheIDEcreatestheLoginFormbeanandopensitintheSourceEditor.Bydefault,theIDEprovidesitwithaStringcallednameandanintcallednumber.Bothfieldshaveaccessormethodsdefinedforthem.Also,theIDEaddsabeandeclarationtothestrutsconfig.xmlfile.Ifyouopenthestrutsconfig.xmlfileintheSourceEditor,youcanseethefollowingdeclaration,whichwasaddedbythewizard:

    TheIDEprovidesnavigationsupportinthestrutsconfig.xmlfile.HolddowntheCtrlkeyandhoveryourmouseovertheLoginFormbean'sfullyqualifiedclassname.Thenamebecomesalink,enablingyoutonavigatedirectlytotheclassintheSourceEditor:

    3. IntheLoginFormbeanintheSourceEditor,createfieldsandaccompanyingaccessormethodsthatcorrespondtothenameandemailtextinputfieldsthatyoucreatedinlogin.jsp.BecausenamehasalreadybeencreatedintheLoginFormskeleton,youonlyneedtoimplementemail.Addthefollowingdeclarationbeneathname(changesinbold):

    privateStringname

    privateStringemail

    Tocreateaccessormethods,placeyourcursoronemailandpressAltInsert.

    SelectGetterandSetter,theninthedialogthatdisplays,selectemail:StringandclickGenerate.Accessormethodsaregeneratedfortheemailfield.

    Note:Youcandeletethedeclarationandaccessormethodsfornumber,asitisnotusedinthistutorial.

  • 14/4/2015 IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial

    https://netbeans.org/kb/docs/web/quickstartwebappsstruts.html 8/14

    CreatinganActionClassTheActionclasscontainsthebusinesslogicintheapplication.Whenformdataisreceived,itistheexecutemethodofanActionobjectthatprocessesthedataanddetermineswhichviewtoforwardtheprocesseddatato.BecausetheActionclassisintegraltotheStrutsframework,NetBeansIDEprovidesyouwithawizard.

    1. IntheProjectswindow,rightclicktheMyStrutsAppprojectnodeandchooseNew>Other.FromtheStrutscategorychooseStrutsActionandclickNext.

    2. IntheNameandLocationpanel,changethenametoLoginAction.

    3. Selectcom.myapp.strutsinthePackagedropdownlist.

    4. Type/logininActionPath.Thisvaluemustmatchthevalueyousetfortheactionattributeofthetagsinlogin.jsp.Makesuresettingsappearasinthescreenshotbelow,thenclickNext.

    5. Inthethirdstepofthewizard,youaregiventheopportunitytoassociatetheActionclasswithaformbean.NoticethattheLoginFormbeanyoupreviouslycreatedislistedasanoptionforActionFormBeanName.Makethefollowingadjustmentstothepanel:

    DeletetheforwardslashfortheInputResourcefield

    SetScopetoRequest(SessionisthedefaultscopesettinginStruts.)

    DeselecttheValidateActionFormBeanoption

    ClickFinish.TheLoginActionclassisgenerated,andthefileopensintheSourceEditor.Alsonotethatthefollowingactionentryisaddedtothestrutsconfig.xmlfile:

    Thenameandscopeattributesapplytotheformbeanthatisassociatedwiththeaction.Specifically,whenanincomingrequestmatches/login,theStrutsframeworkautomaticallyinstantiatesaLoginFormobjectandpopulatesitwiththeformdatasentintherequest.Thedefaultvalueofvalidateissettotrue.Thistellstheframeworktocallthevalidatemethodoftheformbean.Youdeselectedthisoptioninthewizardhoweverbecauseyouwillhandcodesimplevalidationinthenextstep,whichdoesnotrequirethevalidatemethod.

    ImplementingValidationIntheSourceEditor,browsethroughtheLoginActionclassandlookattheexecutemethod:

    publicActionForwardexecute(ActionMappingmapping,ActionFormform,

    HttpServletRequestrequest,HttpServletResponseresponse)

    throwsException{

    returnmapping.findForward(SUCCESS)

    }

    NoticethedefinitionofSUCCESS,listedbeneaththeLoginActionclassdeclaration:

  • 14/4/2015 IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial

    https://netbeans.org/kb/docs/web/quickstartwebappsstruts.html 9/14

    privatefinalstaticStringSUCCESS="success"

    Currently,themapping.findForwardmethodissettounconditionallyforwardanyrequesttoanoutputviewcalledsuccess.Thisisnotreallydesirableyouwanttofirstperformsomesortofvalidationontheincomingdatatodeterminewhethertosendthesuccessview,oranydifferentview.

    AccessingBeanDataandPreparingaForwardingCondition

    SettingUpanErrorMessage

    AccessingBeanDataandPreparingaForwardingCondition

    1. Typeinthefollowingcodewithinthebodyoftheexecutemethod:

    //extractuserdata

    LoginFormformBean=(LoginForm)form

    Stringname=formBean.getName()

    Stringemail=formBean.getEmail()

    Inordertousetheincomingformdata,youneedtotakeexecute'sActionFormargumentandcastitasLoginForm,thenapplythegettermethodsthatyoucreatedearlier.

    2. Typeinthefollowingconditionalclausetoperformvalidationontheincomingdata:

    //performvalidation

    if((name==null)||//nameparameterdoesnotexist

    email==null||//emailparameterdoesnotexist

    name.equals("")||//nameparameterisempty

    email.indexOf("@")==1){//emaillacks'@'

    returnmapping.findForward(FAILURE)

    }

    Atthisstage,theexecutemethodshouldlookasfollows:

    publicActionForwardexecute(ActionMappingmapping,ActionFormform,

    HttpServletRequestrequest,HttpServletResponseresponse)

    throwsException{

    //extractuserdata

    LoginFormformBean=(LoginForm)form

    Stringname=formBean.getName()

    Stringemail=formBean.getEmail()

    //performvalidation

    if((name==null)||//nameparameterdoesnotexist

    email==null||//emailparameterdoesnotexist

    name.equals("")||//nameparameterisempty

    email.indexOf("@")==1){//emaillacks'@'

    returnmapping.findForward(FAILURE)

    }

    returnmapping.findForward(SUCCESS)

    }

    3. AddadeclarationforFAILUREtotheLoginActionclass(changesinbold):

    privatefinalstaticStringSUCCESS="success"

    privatefinalstaticStringFAILURE="failure"

    Usingtheabovelogic,theexecutemethodforwardstherequesttothesuccessviewiftheuserprovidesanentryforbothnameandemailfields,andtheemailenteredcontainsan'@'sign.Otherwise,thefailureviewisforwarded.AswillbedemonstratedbelowinAddingforwardEntriestostrutsconfig.xml,youcansetthefailureviewtopointbacktotheformpage,sothattheuserhasanotherchancetoenterdatainthecorrectformat.

    SettingUpanErrorMessageIftheloginformisreturned,itwouldbegoodtoinformtheuserthatvalidationfailed.Youcanaccomplishthisbyaddinganerrorfieldintheformbean,andanappropriatetagtotheforminlogin.jsp.Finally,intheActionobject,settheerrormessagetobedisplayedintheeventthatthefailureviewischosen.

  • 14/4/2015 IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial

    https://netbeans.org/kb/docs/web/quickstartwebappsstruts.html 10/14

    1. OpenLoginFormandaddanerrorfieldtotheclass:

    //errormessage

    privateStringerror

    2. Addagettermethodandasettermethodforerror,asdemonstratedabove.

    3. Modifythesettermethodsothatitappearsasfollows:

    publicvoidsetError(){

    this.error=

    "Pleaseprovidevalidentriesforboth

    fields"

    }

    4. Openlogin.jspandmakethefollowingchanges:

    &nbsp

    Enteryourname:

    5. InLoginAction,withintheifconditionalclause,addastatementtosettheerrormessagebeforeforwardingthefailurecondition(changesinbold):

    if((name==null)||//nameparameterdoesnotexist

    email==null||//emailparameterdoesnotexist

    name.equals("")||//nameparameterisempty

    email.indexOf("@")==1){//emaillacks'@'

    formBean.setError()returnmapping.findForward(FAILURE)

    }

    YourcompletedLoginActionclassshouldnowappearasfollows:

    publicclassLoginActionextendsorg.apache.struts.action.Action{

    privatefinalstaticStringSUCCESS="success"

    privatefinalstaticStringFAILURE="failure"

    publicActionForwardexecute(ActionMappingmapping,ActionFormform,

    HttpServletRequestrequest,HttpServletResponseresponse)

    throwsException{

    //extractuserdata

    LoginFormformBean=(LoginForm)form

    Stringname=formBean.getName()

    Stringemail=formBean.getEmail()

    //performvalidation

    if((name==null)||//nameparameterdoesnotexist

    email==null||//emailparameterdoesnotexist

    name.equals("")||//nameparameterisempty

    email.indexOf("@")==1){//emaillacks'@'

    formBean.setError()

    returnmapping.findForward(FAILURE)

    }

    returnmapping.findForward(SUCCESS)

  • 14/4/2015 IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial

    https://netbeans.org/kb/docs/web/quickstartwebappsstruts.html 11/14

    }

    }

    AddingforwardEntriestostrutsconfig.xmlInorderfortheapplicationtomatchJSPpageswithforwardingconditionsreturnedbyLoginAction'sexecutemethod,youneedtoaddforwardentriestothestrutsconfig.xmlfile.

    1. Openstrutsconfig.xmlintheSourceEditor,rightclickanywhereintheactionentryforLoginForm,andchooseStruts>AddForward.

    2. IntheAddForwarddialogbox,typesuccessinForwardName.Enterthepathtosuccess.jspintheResourceFilefield(i.e.,/WEBINF/success.jsp).Thedialogboxshouldnowlookasfollows:

    ClickAdd.Notethatthefollowingforwardentrywasaddedtostrutsconfig.xml(changesinbold):

    3. Performthesameactiontoaddaforwardentryforfailure.SettheResourceFilepathto/login.jsp.Thefollowingforwardentryisaddedtostrutsconfig.xml(changesinbold):

    ConfiguringandRunningtheApplicationTheIDEusesanAntbuildscripttobuildandrunyourwebapplication.TheIDEgeneratedthebuildscriptwhenyoucreatedtheproject,basingitontheoptionsyouenteredintheNewProjectwizard.Beforeyoubuildandruntheapplication,youneedtosettheapplication'sdefaultentrypointtologin.jsp.Optionally,youcanalsoaddasimplestylesheettotheproject.

    SettingtheWelcomePage

    AttachingaStylesheet

    RunningtheApplication

    SettingtheWelcomePage

  • 14/4/2015 IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial

    https://netbeans.org/kb/docs/web/quickstartwebappsstruts.html 12/14

    1. IntheProjectswindow,doubleclicktheweb.xmldeploymentdescriptor.ThetabslistedalongthetopoftheSourceEditorprovideyouwithaninterfacetotheweb.xmlfile.ClickonthePagestab.IntheWelcomeFilesfield,enterlogin.jsp.

    NowclickontheSourcetabtoviewthefile.Notethatlogin.jspisnowlistedinthewelcomefileentry:

    login.jsp

    AttachingaStylesheet

    1. Addasimplestylesheettotheproject.Oneeasywaytodothisisbysavingthissamplestylesheettoyourcomputer.Copythefile(CtrlC),thenintheIDE,selecttheWebPagesnodeintheProjectswindowandpressCtrlV).Thefileisaddedtoyourproject.

    2. LinkthestylesheettoyourJSPpagesbyaddingareferencebetweenthetagsofbothlogin.jspandsuccess.jsp:

    RunningtheApplication

    1. IntheProjectswindow,rightclicktheprojectnodeandchooseRun.TheIDEbuildsthewebapplicationanddeploysit,usingtheserveryouspecifiedwhencreatingtheproject.Thebrowseropensanddisplaysthelogin.jsppage.Typeinsomedatathatshouldfailvalidation,i.e.,eitherleaveeitherfieldblank,orenteranemailaddresswithamissing'@'sign:

    WhenyouclickLogin,theloginformpageredisplays,containinganerrormessage:

    Tryenteringdatathatshouldpassvalidation.UponclickingLogin,youarepresentedwiththesuccesspage:

  • 14/4/2015 IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial

    https://netbeans.org/kb/docs/web/quickstartwebappsstruts.html 13/14

    SendUsYourFeedback

    SeeAlsoThisconcludestheIntroductiontotheStrutsFrameworkinNetBeansIDE.ThisdocumentdemonstratedhowtoconstructasimplewebMVCapplicationinNetBeansIDEusingtheStrutsFramework,andintroducedyoutotheIDE'sinterfacefordevelopingwebapplications.YouwereshownhowtouseStrutstagsinJSPpages,temporarilystoreuserdatainaStrutsActionFormbean,andimplementforwardinglogicusingaStrutsActionobject.Youarealsoshownhowtoimplementsimplevalidationtoyourapplication,includingsettingupwarningmessageforafailedloginattempt.

    Forrelatedtutorials,seethefollowingresources:

    AddingSupportforaWebFramework.AgeneralguidedescribinghowtoaddwebframeworksupporttoNetBeansIDEusingthePluginManager.

    IntroductiontotheSpringWebFramework.DescribesthebasicsofusingNetBeansIDEtodevelopwebapplicationsusingtheSpringframework.

    IntroductiontoJavaServerFaces2.0.Adocumentdescribinghowtowireamanagedbeantowebpages,andhowtotakeadvantageofFaceletstemplating..

  • 14/4/2015 IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial

    https://netbeans.org/kb/docs/web/quickstartwebappsstruts.html 14/14

    SiteMap AboutUs Contact Legal&Licences

    Byuseofthiswebsite,youagreetotheNetBeansPoliciesandTermsofUse.2015,OracleCorporationand/oritsaffiliates.Sponsoredby

top related