introduction to the struts web framework - netbeans ide tutorial

14
NetBeans IDE NetBeans Platform Enterprise Plugins Docs & Support Community Search HOME / Docs & Support Introduction to the Struts Web Framework This document takes you through the basics of using NetBeans IDE to develop web applications using the Struts web framework. Struts is an open source framework that extends the Java Servlet API and employs a Model, View, Controller (MVC) architecture. It enables you to create maintainable, extensible, and flexible web applications based on standard technologies, such as JSP pages, JavaBeans, resource bundles, and XML. This tutorial teaches you how to build a simple MVC application that displays a login page and returns a success page upon submitting data that passes validation. You learn several basic features provided by Struts, as well as how these features are implemented using the IDE. Specifically, you use Struts tags in JSP pages, maintain user data with a Struts ActionForm bean, and implement forwarding logic using a Struts Action object. You are also shown how to implement simple validation to your application, including setting up warning message for a failed login attempt. For a more finegrained introduction to Struts, see How does Struts work? on the official Struts website. Also, make use of the IDE's Javadoc Index Search (Help > Javadoc Index Search) to view the Struts Framework API, which is packaged with the Struts libraries. Contents Overview of the Application Setting Up a Struts Application Creating JSP Pages Creating a Login Page Creating a Success Page Creating an ActionForm Bean Creating an Action Class Implementing Validation Accessing Bean Data and Preparing a Forwarding Condition Setting Up an Error Message Adding forward Entries to strutsconfig.xml Configuring and Running the Application Setting the Welcome Page Attaching a Stylesheet Running the Application See Also To complete this tutorial, you need the following software and resources. Software or Resource Version Required NetBeans IDE 7.2, 7.3, 7.4, 8.0, Java EE Java Development Kit (JDK) 7 or 8 GlassFish server or Tomcat servlet container Open Source Edition 3.x or 4.0 version 7.x or 8.x Notes: The Java installation enables you to optionally install the GlassFish server and the Apache Tomcat servlet container. You must install one of these (or register a different server in the IDE) to work through this tutorial. If you need to compare your project with a working solution, you can download the sample application. Overview of the Application When you use Struts, the framework provides you with a controller servlet, ActionServlet, which is defined in the Struts libraries that are included in the IDE, and which is automatically registered in the web.xml deployment descriptor as shown below. The controller servlet uses a strutsconfig.xml file to map incoming requests to Struts Action objects, and instantiate any ActionForm objects associated with the action to temporarily store form data. The Action object processes requests using its execute method, while making use of any data stored in the form bean. Once the Action object processes a request, it stores any new data (i.e., in the form bean, or in a separate result bean), and forwards the results to the appropriate view. Training Java Programming Language Support Oracle Development Tools Support Offering for NetBeans IDE Documentation General Java Development External Tools and Services Java GUI Applications Java EE & Java Web Development Web Services Applications NetBeans Platform (RCP) and Module Development PHP and HTML5 Applications C/C++ Applications Mobile Applications Sample Applications Demos and Screencasts More FAQs Contribute Documentation! Docs for Earlier Releases Choose page language

Upload: ben-avraham

Post on 18-Dec-2015

9 views

Category:

Documents


0 download

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