You are on page 1of 14

14/4/2015

IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial
Choosepagelanguage

NetBeansIDE NetBeansPlatform Enterprise Plugins Docs&Support Community

Search

HOME/Docs&Support

IntroductiontotheStrutsWebFramework
ThisdocumenttakesyouthroughthebasicsofusingNetBeansIDEtodevelopwebapplicationsusingtheStrutswebframework.Strutsisan
opensourceframeworkthatextendstheJavaServletAPIandemploysaModel,View,Controller(MVC)architecture.Itenablesyoutocreate

Training

maintainable,extensible,andflexiblewebapplicationsbasedonstandardtechnologies,suchasJSPpages,JavaBeans,resourcebundles,
andXML.
ThistutorialteachesyouhowtobuildasimpleMVCapplicationthatdisplaysaloginpageandreturnsasuccesspageuponsubmittingdata

JavaProgramming
Language

thatpassesvalidation.YoulearnseveralbasicfeaturesprovidedbyStruts,aswellashowthesefeaturesareimplementedusingtheIDE.
Specifically,youuseStrutstagsinJSPpages,maintainuserdatawithaStrutsActionFormbean,andimplementforwardinglogicusinga

Support

StrutsActionobject.Youarealsoshownhowtoimplementsimplevalidationtoyourapplication,includingsettingupwarningmessagefor
afailedloginattempt.
ForamorefinegrainedintroductiontoStruts,seeHowdoesStrutswork?ontheofficialStrutswebsite.Also,makeuseoftheIDE'sJavadoc
IndexSearch(Help>JavadocIndexSearch)toviewtheStrutsFrameworkAPI,whichispackagedwiththeStrutslibraries.

OracleDevelopmentTools
SupportOfferingfor
NetBeansIDE

Contents
OverviewoftheApplication
SettingUpaStrutsApplication

Documentation
GeneralJavaDevelopment
ExternalToolsand
Services

CreatingJSPPages
CreatingaLoginPage

JavaGUIApplications

CreatingaSuccessPage

JavaEE&JavaWeb
Development

CreatinganActionFormBean

WebServicesApplications

CreatinganActionClass

NetBeansPlatform(RCP)
andModuleDevelopment

ImplementingValidation
AccessingBeanDataandPreparingaForwardingCondition

PHPandHTML5
Applications

SettingUpanErrorMessage

C/C++Applications

AddingforwardEntriestostrutsconfig.xml
ConfiguringandRunningtheApplication
SettingtheWelcomePage

MobileApplications
SampleApplications
DemosandScreencasts

AttachingaStylesheet
RunningtheApplication

More
FAQs

SeeAlso

ContributeDocumentation!
Tocompletethistutorial,youneedthefollowingsoftwareandresources.
SoftwareorResource

VersionRequired

NetBeansIDE

7.2,7.3,7.4,8.0,JavaEE

DocsforEarlierReleases

JavaDevelopmentKit(JDK) 7or8
GlassFishserver
or
Tomcatservletcontainer

OpenSourceEdition3.xor4.0

version7.xor8.x

Notes:
TheJavainstallationenablesyoutooptionallyinstalltheGlassFishserverandtheApacheTomcatservletcontainer.Youmustinstall
oneofthese(orregisteradifferentserverintheIDE)toworkthroughthistutorial.
Ifyouneedtocompareyourprojectwithaworkingsolution,youcandownloadthesampleapplication.

OverviewoftheApplication
WhenyouuseStruts,theframeworkprovidesyouwithacontrollerservlet,ActionServlet,whichisdefinedintheStrutslibrariesthatare
includedintheIDE,andwhichisautomaticallyregisteredintheweb.xmldeploymentdescriptorasshownbelow.Thecontrollerservlet
usesastrutsconfig.xmlfiletomapincomingrequeststoStrutsActionobjects,andinstantiateanyActionFormobjects
associatedwiththeactiontotemporarilystoreformdata.TheActionobjectprocessesrequestsusingitsexecutemethod,whilemaking
useofanydatastoredintheformbean.OncetheActionobjectprocessesarequest,itstoresanynewdata(i.e.,intheformbean,orina
separateresultbean),andforwardstheresultstotheappropriateview.

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

1/14

14/4/2015

IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial

DevelopingaStrutsapplicationissimilartodevelopinganyotherkindofwebapplicationinNetBeansIDE.However,youcomplementyour
webdevelopmenttoolkitbytakingadvantageoftheStrutssupportprovidedbytheIDE.Forexample,youusetemplatesintheIDEtocreate
StrutsActionobjectsandActionFormbeans.Uponcreation,theIDEautomaticallyregisterstheseclassesinthestruts

config.xmlfileandletsyouextendthisfileveryeasilyusingmenuitemsintheSourceEditor'srightclickmenu.Becausemanyweb
applicationsuseJSPpagesfortheview,StrutsalsoprovidescustomtaglibrarieswhichfacilitateinteractionwithHTMLforms.Withinthe
IDE'sSourceEditor,youcaninvokecodecompletionandJavadocsupportthathelpsyoutoworkefficientlywiththeselibraries.
Thefollowingstepsdemonstratehowtocreateasimpleformthatcollectsuserdata,performssimplevalidation,andoutputsthedataona
successpage.

SettingUpaStrutsApplication
IntheIDE,aStrutsapplicationisnothingmorethananormalwebapplicationaccompaniedbytheStrutslibrariesandconfigurationfiles.
YoucreateaStrutsapplicationinthesamewayasyoucreateanyotherwebapplicationintheIDEusingtheNewWebApplicationwizard,
withtheadditionalstepofindicatingthatyouwanttheStrutslibrariesandconfigurationfilestobeincludedinyourapplication.
1. ChooseFile>NewProject(CtrlShiftNShiftNonMac)fromthemainmenu.SelectJavaWebinthelistofCategoriesandthen
selectWebApplicationinthelistofProjects.ClickNext.
2. IntheNameandLocationpanel,enterMyStrutsAppforProjectNameandclickNext.
3. IntheServerandSettingspanel,selecttheservertowhichyouwanttodeployyourapplication.Onlyserversthatareregisteredwith
theIDEarelisted.(Toregisteraserver,clickAddnexttotheServerdropdownlist.)Also,notethattheContextPathtoyourdeployed
applicationbecomes/MyStrutsApp.ClickNext.
4. SelectStrutsintheFrameworkspanel.

Forpurposesofthistutorial,donotchangeanyoftheconfigurationvaluesinthelowerregionofthispanel.Thewizarddisplaysthe
followingconfigurationoptions.
ActionServletName:ThenameoftheStrutsactionservletusedintheapplication.Theweb.xmldeploymentdescriptor

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

2/14

14/4/2015

IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial
containsanentryfortheactionservletandspecifiestheappropriateStrutsspecificparameters,suchasthepathtotheservlet
classwithintheStrutslibraryandtothestrutsconfig.xmlconfigurationfilewithintheapplication.
ActionURLPattern:SpecifiesthepatternsofincomingrequestswhicharemappedtotheStrutsactioncontroller.This
generatesamappingentryinthedeploymentdescriptor.Bydefault,onlythe*.dopatternismapped.
ApplicationResource:Letsyouspecifytheresourcebundlewhichwillbeusedinthestrutsconfig.xmlfilefor
localizingmessages.Bydefault,thisiscom.myapp.struts.ApplicationResource.
AddStrutsTLDs:LetsyougeneratetaglibrarydescriptorsfortheStrutstaglibraries.AtaglibrarydescriptorisanXML
documentwhichcontainsadditionalinformationabouttheentiretaglibraryaswellaseachindividualtag.Ingeneralthisis
notnecessary,becauseyoucanrefertoonlineURIsratherthanlocalTLDfiles.
5. ClickFinish.TheIDEcreatestheprojectfolderinyourfilesystem.AswithanywebapplicationintheIDE,theprojectfoldercontains
allofyoursourcesandtheIDE'sprojectmetadata,suchastheAntbuildscript.However,yourwebapplicationinadditionhasallof
theStrutslibrariesonitsclasspath.Notonlyaretheyontheapplication'sclasspath,buttheyareincludedintheprojectandwillbe
packagedwithitlaterwhenyoubuildtheproject.
TheprojectopensintheIDE.TheProjectswindowisthemainentrypointtoyourprojectsources.Itshowsalogicalviewofimportantproject
contents.Forexample,ifyouexpandseveralnodeswithinthenewproject,itmayappearasfollows:

Note:UsetheFileswindow(Window>Files)toseeallofyourprojectcontentsinadirectorybasedview.
TheStrutsspecificconfigurationfiles,aswellastheapplication'sdeploymentdescriptor,areconvenientlyplacedwithintheConfiguration
Filesfolder.Openthedeploymentdescriptor(doubleclicktheweb.xmlfilenodetohaveitdisplayintheSourceEditor).Inordertohandle
Strutsprocessing,amappingisprovidedfortheStrutscontrollerservlet.

<servlet>
<servletname>action</servletname>
<servletclass>org.apache.struts.action.ActionServlet</servletclass>
<initparam>
<paramname>config</paramname>
<paramvalue>/WEBINF/strutsconfig.xml</paramvalue>
</initparam>
<initparam>
<paramname>debug</paramname>
<paramvalue>2</paramvalue>

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

3/14

14/4/2015

IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial
</initparam>
<initparam>
<paramname>detail</paramname>
<paramvalue>2</paramvalue>
</initparam>
<loadonstartup>2</loadonstartup>
</servlet>
<servletmapping>
<servletname>action</servletname>
<urlpattern>*.do</urlpattern>
</servletmapping>
Above,theStrutscontrollerservletisnamedactionandisdefinedintheStrutslibrary
(org.apache.struts.action.ActionServlet).Itissettohandleallrequeststhatsatisfythe*.domapping.Inaddition,
initializationparametersfortheservletarespecifiedbymeansofthestrutsconfig.xmlfile,alsocontainedintheWEBINFfolder.

CreatingJSPPages
BeginbycreatingtwoJSPpagesfortheapplication.Thefirstdisplaysaform.Thesecondistheviewreturnedwhenloginissuccessful.
CreatingaLoginPage
CreatingaSuccessPage

CreatingaLoginPage
1. RightclicktheMyStrutsAppprojectnode,chooseNew>JSP,andnamethenewfilelogin.ClickFinish.Thelogin.jsp
fileopensintheSourceEditor.
2. IntheSourceEditor,changethecontentofboththe<title>and<h1>tags(or<h2>tags,dependingontheIDEversionyou
areusing)toLoginForm.
3. Addthefollowingtwotaglibdirectivestothetopofthefile:

<%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>
<%@tagliburi="http://struts.apache.org/tagshtml"prefix="html"%>
ManywebapplicationsuseJSPpagesforviewsintheMVCparadigm,soStrutsprovidescustomtaglibrarieswhichfacilitate
interactionwithHTMLforms.ThesecanbeeasilyappliedtoaJSPfileusingtheIDE'ssupportforcodecompletion.Whenyou
typeintheSourceEditor,theIDEprovidesyouwithcodecompletionforStrutstags,aswellastheStrutsJavadoc.Youcanalso
invokecodecompletionmanuallybypressingCtrlSpace:

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

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

4/14

14/4/2015

IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial
webapplication.Forexample,belowyoureplacecommonhtmlformtagswithStruts'<html:form>tags.Onebenefitthis
providesisthatitcausestheservertolocateorcreateabeanobjectthatcorrespondstothevalueprovidedforhtml:form's

actionelement.
4. Belowthe<h1>(or<h2>)tags,addthefollowing:

<html:formaction="/login">
<html:submitvalue="Login"/>
</html:form>
WheneveryoufinishtypingintheSourceEditor,youcantidyupthecodebyrightclickingandchoosingFormat(AltShift
F).
5. InthePalette(Window>Palette)intherightregionoftheIDE,dragaTableitemfromtheHTMLcategorytoapointjustabovethe

<html:submitvalue="Login"/>line.TheInsertTabledialogboxdisplays.Settherowsto3,columnsto2,andleave
allothersettingsat0.Laterinthetutorial,youwillattachastylesheettoaffectthetabledisplay.

ClickOK,thenoptionallyreformatthecode(AltShiftF).Theforminlogin.jspnowlooksasfollows:

<html:formaction="/login">
<tableborder="0">
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<html:submitvalue="Login"/>
</html:form>
Note:Youcansafelydeletethe<thead>tablerow,asitisnotusedinthistutorial.
6. Inthefirsttablerow,enterthefollowing(changesinbold):

<tr>

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

5/14

14/4/2015

IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial
<td>Enteryourname:</td>
<td><html:textproperty="name"/></td>
</tr>
7. Inthesecondtablerow,enterthefollowing(changesinbold):

<tr>
<td>Enteryouremail:</td>
<td><html:textproperty="email"/></td>
</tr>
Thehtml:textelementenablesyoutomatchtheinputfieldsfromtheformwithpropertiesintheformbeanthatwillbecreated
inthenextstep.Soforexample,thevalueofpropertymustmatchafielddeclaredintheformbeanassociatedwiththisform.
8. Movethe<html:submitvalue="Login"/>elementintothesecondcolumnofthethirdtablerow,sothatthethirdtablerowappears
asfollows(changesinbold):

<tr>
<td></td>
<td><html:submitvalue="Login"/></td>
</tr>
Atthisstage,yourloginformshouldlookasfollows:

<html:formaction="/login">
<tableborder="0">
<tbody>
<tr>
<td>Enteryourname:</td>
<td><html:textproperty="name"/></td>
</tr>
<tr>
<td>Enteryouremail:</td>
<td><html:textproperty="email"/></td>
</tr>
<tr>
<td></td>
<td><html:submitvalue="Login"/></td>
</tr>
</tbody>
</table>
</html:form>

CreatingaSuccessPage
1. RightclicktheMyStrutsAppprojectnode,chooseNew>JSP,andnamethenewfilesuccess.IntheFolderfield,clickthe
adjacentBrowsebuttonandselectWEBINFfromthedialogthatdisplays.ClickSelectFoldertoenterWEBINFintheFolder
field.AnyfilescontainedintheWEBINFfolderarenotdirectlyaccessibletoclientrequests.Inorderforsuccess.jsptobe
properlydisplayed,itmustcontainprocesseddata.ClickFinish.
2. IntheSourceEditor,changethecontentofthenewlycreatedpagetothefollowing:

<head>
<metahttpequiv="ContentType"content="text/htmlcharset=UTF8">
<title>LoginSuccess</title>
</head>
<body>
<h1>Congratulations!</h1>
<p>Youhavesuccessfullyloggedin.</p>
<p>Yournameis:.</p>
<p>Youremailaddressis:.</p>
</body>
3. Addabeantaglibdirectivetothetopofthefile:

<%@tagliburi="http://struts.apache.org/tagsbean"prefix="bean"%>

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

6/14

14/4/2015

IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial
4. Addthefollowing<bean:write>tags(changesinbold):

<p>Yournameis:<bean:writename="LoginForm"property="name"/>.</p>
<p>Youremailaddressis:<bean:writename="LoginForm"property="email"/>.</p>
Byemployingthe<bean:write>tags,youmakeuseofthebeantaglibtolocatetheActionFormbeanyouareaboutto
create,anddisplaytheuserdatasavedfornameandemail.

CreatinganActionFormBean
AStrutsActionFormbeanisusedtopersistdatabetweenrequests.Forexample,ifausersubmitsaform,thedataistemporarilystoredin
theformbeansothatitcaneitherberedisplayedintheformpage(ifthedataisinaninvalidformatorifloginfails)ordisplayedinalogin
successpage(ifdatapassesvalidation).
1. RightclicktheMyStrutsAppprojectnodeandchooseNew>Other.UnderCategorieschooseStruts,thenunderFileTypes
chooseStrutsActionFormBean.ClickNext.
2. TypeinLoginFormfortheClassName.Thenselectcom.myapp.strutsinthePackagedropdownlistandclickFinish.
TheIDEcreatestheLoginFormbeanandopensitintheSourceEditor.Bydefault,theIDEprovidesitwithaStringcalledname
andanintcallednumber.Bothfieldshaveaccessormethodsdefinedforthem.Also,theIDEaddsabeandeclarationtothe

strutsconfig.xmlfile.Ifyouopenthestrutsconfig.xmlfileintheSourceEditor,youcanseethefollowingdeclaration,
whichwasaddedbythewizard:

<formbeans>
<formbeanname="LoginForm"type="com.myapp.struts.LoginForm"/>
</formbeans>
TheIDEprovidesnavigationsupportinthestrutsconfig.xmlfile.HolddowntheCtrlkeyandhoveryourmouseoverthe

LoginFormbean'sfullyqualifiedclassname.Thenamebecomesalink,enablingyoutonavigatedirectlytotheclassintheSource
Editor:

3. IntheLoginFormbeanintheSourceEditor,createfieldsandaccompanyingaccessormethodsthatcorrespondtothenameand

emailtextinputfieldsthatyoucreatedinlogin.jsp.BecausenamehasalreadybeencreatedintheLoginFormskeleton,you
onlyneedtoimplementemail.
Addthefollowingdeclarationbeneathname(changesinbold):
privateStringname
privateStringemail
Tocreateaccessormethods,placeyourcursoronemailandpressAltInsert.

SelectGetterandSetter,theninthedialogthatdisplays,selectemail:StringandclickGenerate.Accessormethodsare
generatedfortheemailfield.
Note:Youcandeletethedeclarationandaccessormethodsfornumber,asitisnotusedinthistutorial.

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

7/14

14/4/2015

IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial

CreatinganActionClass
TheActionclasscontainsthebusinesslogicintheapplication.Whenformdataisreceived,itistheexecutemethodofanAction
objectthatprocessesthedataanddetermineswhichviewtoforwardtheprocesseddatato.BecausetheActionclassisintegraltothe
Strutsframework,NetBeansIDEprovidesyouwithawizard.
1. IntheProjectswindow,rightclicktheMyStrutsAppprojectnodeandchooseNew>Other.FromtheStrutscategorychooseStruts
ActionandclickNext.
2. IntheNameandLocationpanel,changethenametoLoginAction.
3. Selectcom.myapp.strutsinthePackagedropdownlist.
4. Type/logininActionPath.Thisvaluemustmatchthevalueyousetfortheactionattributeofthe<html:form>tagsin

login.jsp.Makesuresettingsappearasinthescreenshotbelow,thenclickNext.

5. Inthethirdstepofthewizard,youaregiventheopportunitytoassociatetheActionclasswithaformbean.Noticethatthe

LoginFormbeanyoupreviouslycreatedislistedasanoptionforActionFormBeanName.Makethefollowingadjustmentstothe
panel:
DeletetheforwardslashfortheInputResourcefield
SetScopetoRequest(SessionisthedefaultscopesettinginStruts.)
DeselecttheValidateActionFormBeanoption
ClickFinish.TheLoginActionclassisgenerated,andthefileopensintheSourceEditor.Alsonotethatthefollowingaction
entryisaddedtothestrutsconfig.xmlfile:

<actionmappings>
<actionname="LoginForm"path="/login"scope="request"
type="com.myapp.struts.LoginAction"validate="false"/>
<actionpath="/Welcome"forward="/welcomeStruts.jsp"/>
</actionmappings>
Thenameandscopeattributesapplytotheformbeanthatisassociatedwiththeaction.Specifically,whenanincomingrequest
matches/login,theStrutsframeworkautomaticallyinstantiatesaLoginFormobjectandpopulatesitwiththeformdatasentin
therequest.Thedefaultvalueofvalidateissettotrue.Thistellstheframeworktocallthevalidatemethodoftheformbean.
Youdeselectedthisoptioninthewizardhoweverbecauseyouwillhandcodesimplevalidationinthenextstep,whichdoesnot
requirethevalidatemethod.

ImplementingValidation
IntheSourceEditor,browsethroughtheLoginActionclassandlookattheexecutemethod:

publicActionForwardexecute(ActionMappingmapping,ActionFormform,
HttpServletRequestrequest,HttpServletResponseresponse)
throwsException{
returnmapping.findForward(SUCCESS)
}
NoticethedefinitionofSUCCESS,listedbeneaththeLoginActionclassdeclaration:

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

8/14

14/4/2015

IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial

privatefinalstaticStringSUCCESS="success"
Currently,themapping.findForwardmethodissettounconditionallyforwardanyrequesttoanoutputviewcalledsuccess.Thisis
notreallydesirableyouwanttofirstperformsomesortofvalidationontheincomingdatatodeterminewhethertosendthesuccessview,
oranydifferentview.
AccessingBeanDataandPreparingaForwardingCondition
SettingUpanErrorMessage

AccessingBeanDataandPreparingaForwardingCondition
1. Typeinthefollowingcodewithinthebodyoftheexecutemethod:

//extractuserdata
LoginFormformBean=(LoginForm)form
Stringname=formBean.getName()
Stringemail=formBean.getEmail()
Inordertousetheincomingformdata,youneedtotakeexecute'sActionFormargumentandcastitasLoginForm,then
applythegettermethodsthatyoucreatedearlier.
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,theexecutemethodforwardstherequesttothesuccessviewiftheuserprovidesanentryforbothnameand

emailfields,andtheemailenteredcontainsan'@'sign.Otherwise,thefailureviewisforwarded.Aswillbedemonstratedbelowin
AddingforwardEntriestostrutsconfig.xml,youcansetthefailureviewtopointbacktotheformpage,sothattheuser
hasanotherchancetoenterdatainthecorrectformat.

SettingUpanErrorMessage
Iftheloginformisreturned,itwouldbegoodtoinformtheuserthatvalidationfailed.Youcanaccomplishthisbyaddinganerrorfield
intheformbean,andanappropriate<bean:write>tagtotheforminlogin.jsp.Finally,intheActionobject,settheerror
messagetobedisplayedintheeventthatthefailureviewischosen.

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

9/14

14/4/2015

IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial
1. OpenLoginFormandaddanerrorfieldtotheclass:

//errormessage
privateStringerror
2. Addagettermethodandasettermethodforerror,asdemonstratedabove.
3. Modifythesettermethodsothatitappearsasfollows:

publicvoidsetError(){
this.error=
"<spanstyle='color:red'>Pleaseprovidevalidentriesforboth
fields</span>"
}
4. Openlogin.jspandmakethefollowingchanges:

<html:formaction="/login">
<tableborder="0">
<tbody>
<tr>
<tdcolspan="2">
<bean:writename="LoginForm"property="error"filter="false"/>
&nbsp</td>
</tr>
<tr>
<td>Enteryourname:</td>
<td><html:textproperty="name"/></td>
</tr>
5. InLoginAction,withintheifconditionalclause,addastatementtosettheerrormessagebeforeforwardingthefailure
condition(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)

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

10/14

14/4/2015

IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial
}
}

AddingforwardEntriestostrutsconfig.xml
InorderfortheapplicationtomatchJSPpageswithforwardingconditionsreturnedbyLoginAction'sexecutemethod,youneedtoadd

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

2. IntheAddForwarddialogbox,typesuccessinForwardName.Enterthepathtosuccess.jspintheResourceFilefield(i.e.,

/WEBINF/success.jsp).Thedialogboxshouldnowlookasfollows:

ClickAdd.Notethatthefollowingforwardentrywasaddedtostrutsconfig.xml(changesinbold):

<actionname="LoginForm"path="/login"scope="request"
type="com.myapp.struts.LoginAction"validate="false">
<forwardname="success"path="/WEBINF/success.jsp"/>
</action>
3. Performthesameactiontoaddaforwardentryforfailure.SettheResourceFilepathto/login.jsp.Thefollowingforward
entryisaddedtostrutsconfig.xml(changesinbold):

<forwardname="success"path="/WEBINF/success.jsp"/>
<forwardname="failure"path="/login.jsp"/>

ConfiguringandRunningtheApplication
TheIDEusesanAntbuildscripttobuildandrunyourwebapplication.TheIDEgeneratedthebuildscriptwhenyoucreatedtheproject,
basingitontheoptionsyouenteredintheNewProjectwizard.Beforeyoubuildandruntheapplication,youneedtosettheapplication's
defaultentrypointtologin.jsp.Optionally,youcanalsoaddasimplestylesheettotheproject.
SettingtheWelcomePage
AttachingaStylesheet
RunningtheApplication

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

11/14

14/4/2015

IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial
1. IntheProjectswindow,doubleclicktheweb.xmldeploymentdescriptor.ThetabslistedalongthetopoftheSourceEditorprovide
youwithaninterfacetotheweb.xmlfile.ClickonthePagestab.IntheWelcomeFilesfield,enterlogin.jsp.

NowclickontheSourcetabtoviewthefile.Notethatlogin.jspisnowlistedinthewelcomefileentry:

<welcomefile>login.jsp</welcomefile>

AttachingaStylesheet
1. Addasimplestylesheettotheproject.Oneeasywaytodothisisbysavingthissamplestylesheettoyourcomputer.Copythefile
(CtrlC),thenintheIDE,selecttheWebPagesnodeintheProjectswindowandpressCtrlV).Thefileisaddedtoyourproject.
2. LinkthestylesheettoyourJSPpagesbyaddingareferencebetweenthe<head>tagsofbothlogin.jspandsuccess.jsp:

<linkrel="stylesheet"type="text/css"href="stylesheet.css">

RunningtheApplication
1. IntheProjectswindow,rightclicktheprojectnodeandchooseRun.TheIDEbuildsthewebapplicationanddeploysit,usingthe
serveryouspecifiedwhencreatingtheproject.Thebrowseropensanddisplaysthelogin.jsppage.Typeinsomedatathat
shouldfailvalidation,i.e.,eitherleaveeitherfieldblank,orenteranemailaddresswithamissing'@'sign:

WhenyouclickLogin,theloginformpageredisplays,containinganerrormessage:

Tryenteringdatathatshouldpassvalidation.UponclickingLogin,youarepresentedwiththesuccesspage:

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

12/14

14/4/2015

IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial

SendUsYourFeedback

SeeAlso
ThisconcludestheIntroductiontotheStrutsFrameworkinNetBeansIDE.ThisdocumentdemonstratedhowtoconstructasimplewebMVC
applicationinNetBeansIDEusingtheStrutsFramework,andintroducedyoutotheIDE'sinterfacefordevelopingwebapplications.You
wereshownhowtouseStrutstagsinJSPpages,temporarilystoreuserdatainaStrutsActionFormbean,andimplementforwarding
logicusingaStrutsActionobject.Youarealsoshownhowtoimplementsimplevalidationtoyourapplication,includingsettingupwarning
messageforafailedloginattempt.
Forrelatedtutorials,seethefollowingresources:
AddingSupportforaWebFramework.AgeneralguidedescribinghowtoaddwebframeworksupporttoNetBeansIDEusingthe
PluginManager.
IntroductiontotheSpringWebFramework.DescribesthebasicsofusingNetBeansIDEtodevelopwebapplicationsusingtheSpring
framework.
IntroductiontoJavaServerFaces2.0.Adocumentdescribinghowtowireamanagedbeantowebpages,andhowtotakeadvantage
ofFaceletstemplating..

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

13/14

14/4/2015

IntroductiontotheStrutsWebFrameworkNetBeansIDETutorial

SiteMap

AboutUs

Contact

Legal&Licences

Byuseofthiswebsite,youagreetotheNetBeansPoliciesandTermsofUse.2015,OracleCorporationand/oritsaffiliates.Sponsoredby

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

14/14