A Stripes 15 Test Drive.docx
- 文档编号:10696096
- 上传时间:2023-02-22
- 格式:DOCX
- 页数:18
- 大小:48.49KB
A Stripes 15 Test Drive.docx
《A Stripes 15 Test Drive.docx》由会员分享,可在线阅读,更多相关《A Stripes 15 Test Drive.docx(18页珍藏版)》请在冰豆网上搜索。
AStripes15TestDrive
AStripes1.5TestDrive
By FredericDaoud
01Dec2008|TheServerS
Stripesisasimpleandpowerfulaction-basedJavawebapplicationframework.Version1.5hasrecentlybeenreleasedwithlotsofcoolfeatures,sowhydon'twetakeitoutforatestdrive?
We'llgetatasteofhoweasyitistodevelopawebapplicationwithStripesbywritingasimpleexample,whereauserfillsoutaformtoregisterandthenlogsintoaccesstheapplication.
ActionBeans
ThefirstthingtoknowaboutStripesisthatyouwriteactionbeanstorespondtorequests.Actionbeansareso-calledbecausetheyencapsulatebothanaction(arequestthatoccurred)andoneormorebeans(referencestoyourmodeldata).Intermsofcode,anactionbeanisaclassthatimplementstheActionBeaninterface:
publicinterfaceActionBean
{
publicActionBeanContextgetContext();
publicvoidsetContext(ActionBeanContextcontext);
}
Justagetterandasetterfortheactionbeancontext,whichStripesautomaticallyprovidestoactionbeans.TheactionbeancontextcontainssuchinformationastheHttpServletRequestandHttpServletResponseobjects,theServletContext,theLocaleassociatedtothecurrentrequest,andsoon.WhileStripesdoesnotrequireyoutoworkdirectlywiththeseobjects,it'snicetoknowthattheyarethereforeasyaccessifyoudoneedthem.
Usually,you'llwanttoimplementtheActionBeaninterfaceonceandforallinabaseclass:
BaseActionBean.java
publicabstractclassBaseActionBeanimplementsActionBean
{
privateActionBeanContextcontext;
publicActionBeanContextgetContext()
{
returncontext;
}
publicvoidsetContext(ActionBeanContextcontext)
{
this.context=context;
}
}
AllyourconcreteactionbeanscannowextendBaseActionBean.Thisalsogivesyouaplaceforcodethatyouwanttomakeavailabletoallyouractionbeans.
EventHandlers
Next,aneventhandlerisamethodinanactionbeanthatgetsinvokedbyStripestorespondtoarequest.Youcanhaveoneormoreeventhandlersinanactionbean.Therearenorestrictionsonthemethodnamenortheexceptionsthatitmaythrow.What'simportantisthatthemethodhavenoparametersandreturnaResolution(moreonresolutionsinaminute),asin:
publicResolutiondoSomething(){//...}
Eventhandlershaveaname,whichisthenameofthemethodbydefault(doSomethingintheexampleabove).Youcanoverridethenamewiththe@HandlesEventannotation,asintheexamplebelowwheretheeventwillbenamedanotherName:
@HandlesEvent("anotherName")
publicResolutiondoSomething(){//...}
Youuseeventhandlernamesinrequest-triggeringelementssuchaslinksandformsubmitbuttons.Forexample,youcancreatealinkthatinvokesthedoSomethingeventdefinedintheorg.stripesbook.article.action.SomeActionBeanclasswiththiscodeinyourJSP:
linkbeanclass="org.stripesbook.article.action.SomeActionBean"event="doSomething">Clickme
link>
Here'stheequivalentforaformsubmitbutton:
formbeanclass="org.stripesbook.article.action.SomeActionBean"><%--forminputcontrols...--%> submitname="doSomething"value="Pressme"/> form> Noticehowclearandsimplethatis.Thefullyqualifiedclassnameoftheactionbeanandthenameoftheeventhandlermethodarerightthere.Noguesswork,andnoconfigurationfiles. Resolutions AresolutionisreturnedbyaneventhandlertotellStripeswheretogonexttoproducearesponsetotheclient.Resolutionisasimpleinterface: publicinterfaceResolution { voidexecute(HttpServletRequestrequest,HttpServletResponseresponse)throwsException; } Stripesprovidesafewready-to-useimplementations.ThemostcommonlyusedisprobablytheForwardResolution,whichforwardstherequesttoaviewtemplate,suchasaJSP: returnnewForwardResolution("/path/to/your.jsp"); (Note: I'musingJSPinthisarticle,butStripesworksequallywellwithFreeMarker.) Youcanalsoforwardtoanotheractionbeanandevent: returnnewForwardResolution(SomeActionBean.class,"doSomething"); Again,youcanseehowclearitistohavethepathtotheJSPortheactionbeanclassandmethodnamerightthereinsteadofburiedinaconfigurationfile. StripesalsoincludesRedirectResolutiontoredirecttherequest,StreamingResolutiontostreamdatabacktotheclient,JavaScriptResolutiontoreturndataasaJavaScriptobject,andErrorResolutiontoreturnanHTTPerrorcode. ATypicalRegister-Activate-LoginExample That'senoughtheory.Let'stakeStripesoutforatestdrivebybuildingasimpleregister-activate-loginexample.Ausermustfirstregister,thenactivatetheaccountwithanactivationcode(normallysentbyemailtoconfirmthattheaddressisvalid,butwe'lljustuseahardcodedactivationcodeforthisexample),andfinallylogintoenterthesecuredareaoftheapplication,asillustratedbelow. We'llstartwithasimplemodel,theUserclass: User.java packageorg.stripesbook.article.model; publicclassUser{ privateStringemail; privateStringusername; privateStringpassword; privateStringactivationCode; privatebooleanactivated; /*Gettersandsetters...*/ } Next,let'sbuildtheregistrationpage. TheRegistrationPage Theregistrationpageiswheretheusercreatesanaccount.Here'sascreenshotofthepage: We'llstartbywritingtheactionbeanformanagingregistration,RegisterActionBean.java: RegisterActionBean.java packageorg.stripesbook.article.action; @UrlBinding("/register") publicclassRegisterActionBeanextendsBaseActionBean { privateUseruser; privateStringconfirmPassword; /*GettersandsettersforuserandconfirmPassword*/ @DefaultHandler publicResolutionview() { returnnewForwardResolution("/WEB-INF/jsp/register.jsp"); } publicResolutionregister() { //Setrandomactivationcode;we'lljusthardcodeavalueforthisexampleuser.setActivationCode("A1B2");//Savetheusertothe"database"Database.addUser(user); returnnewRedirectResolution(ActivateActionBean.class).addParameter("user.username",user.getUsername());} publicUsergetUser(){ returnuser; } publicvoidsetUser(Useruser){ this.user=user;} publicStringgetConfirmPassword() {returnconfirmPassword;} publicvoidsetConfirmPassword(StringconfirmPassword){this.confirmPassword=confirmPassword;} Withthe@UrlBindingthatwedefined,wecanaccesstheregistrationpagewith[http: //localhost: 8080/stripes-article/register].Thattargetstheactionbean'sdefaulteventhandler,whichisviewbecauseitisannotatedwith@DefaultHandler.Themethodforwardstoregister.jsp,whichdisplaystheregistrationform. Here'swhattheinterestingpartoftheJSPfortheregistrationpagelookslike: register.jsp <%@taglibprefix="s"uri="%> formbeanclass="org.stripesbook.article.action.RegisterActionBean"> Email: textname="user.email"/> Username: textname="user.username"/> Password: passwordname="user.password"/> Confirmpassword: passwordname="confirmPassword"/> submitname="register"value="Register"/> form> Ifyou'veregisteredbuthaven'tactivatedyouraccount, linkbeanclass="org.stripesbook.article.action.ActivateActionBean">clickhere link> Ifyouraccountisalreadyactive,youcanproceedto linkbeanclass="org.stripesbook.article.action.LoginActionBean">login link> NoticethedeclarationoftheStripestaglibraryatthetop.Next,wehaveaformwiththefourtextfieldsforenteringtheemail,username,password,andpasswordconfirmation.Thevaluesenteredbytheuserareboundtothecorrespondingpropertiesintheactionbean,accordingtoeachfield'sname=attribute.Thisworksevenfornestedproperties,suchasuser.email.StripeswillbindthevaluebycallinggetUser().setEmail(value)ontheactionbeanandwillevencreateanewUserobjectautomatically.YoujustdeclarethepropertiesintheactionbeanwithoutworryingaboutdreadedNullPointerExceptions. Sincethename=ofthe submit>buttonisregister,Stripesinvokesregister()whentheuserpressestheRegisterbutton.Thatcreatestheuserinthedatabaseandredirectstotheactivationpage. Beforegoinganyfurther,let'sdiscusshowweaddsomevalidationtotheregistrationpage. Validation Let'saddthesevalidationstotheregistrationform: ∙Allfieldsarerequired ∙Theemailmustbeinvalidemailaddressformat ∙Thepasswordandconfirmpasswordmustmatch. Wecanachievethisquiteeasilywithvalidationannotationsontheuserfield: RegisterActionBean.java @ValidateNestedProperties( {@Validate(field="email",required=true,converter=EmailTypeConverter.class), @Validate(field="username",required=true), @Validate(field="password",required=true,expression="${thiseqconfirmPassword}")}) privateUseruser; Validationannotationsmustbeinanactionbean,butwecanstillvalidatefieldswithinamodelobjectbyusing@ValidateNestedPropertiesasinthecodeabove.Next,@Validatevalidatesafieldandhasbuilt-inelementsforcommontypesofvalidation.Hereweareusingrequired=truetomakeafieldrequired,andconverter=EmailTypeConverter.classtovalidatetheformatoftheemailaddress.Wecanvalidatethatthepasswordsmatchwith``expression="${thiseqconfirmPassword}",where``thisautomaticallyreferstothefieldbeingvalidated,andconfirmPasswordisthecorrespondingpropertyintheactionbean.ThesyntaxoftheexpressionisthesameasaregularJSPELexpression. Notethatyoudon'thavetoworryaboutextraspacesatthebeginningorattheendofthein
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Stripes 15 Test Drive