Anda di halaman 1dari 15

Lab 1

Client-side Development
using HTML, Javascript and CSS
Authors:
Sahand Sdjadee
Alexander Kazen
Gustav Bylund
Per Jonsson
Tobias Jansson

Spring 2015
TDDD97 Web Programming
http://www.ida.liu.se/~TDDD97/
Department of Computer and Information Science (IDA)
Linkping University
Sweden

1.Introduction

In this first lab, you will use the components of HTML5, that is HTML, CSS and JavaScript, to
implementthe clientsideof Twidder.Youhavealsobeenprovidedaserverstub,whichworksasyour
notyet writtenserversidecode. This helpsyouhaveafullyfunctionalapplicationbytheendoflab1
and be able to see the output at an early stage.Later on, whenyouhave yourownserversidecode
implemented, the serverstub will be removed from the application and you will use your own
serversidecode.Youwillreadmoreabouttheprovidedserverstubinsection2.
Each lab has been divided into several continuous steps which each addsa new piecetothefinal
application and make the product more complete. You are required to develop step by step and
implement each step according to the instructions. Once you are finished with each lab, you will
present your work to your responsible lab assistant. For more specific information about the
presentation andevaluation process oflab 1, pleasechecksection 7: PresentationandEvaluation.For
moreinformationabouttheexaminationprocess,pleasecheckthecoursepage.

Requirements
Bytheendoflab1,thefollowingfunctionalrequirementsshallbemet.

Functional
Theusershallbeabletosignup,signinandsignout.
Theusershallbeabletoviewhis/herownpersonalinformationprovidedduringsignup,
everythingexcludingthepassword,oncesignedin.
Theusershallownamessagewallwhichotherusersandhimself/herselfcanpostmessageson
it.
Theusershallbeabletorefreshhis/herownwalltocheckforanynewlypostedmessages,
withoutrefreshingtherestofcontent.Inotherwords,thebrowsersrefreshbuttonshallnotbe
used.
Theusershallbeabletoviewanotheruserspersonalinformation,everythingexcludingtheir
password,andmessagewallbyprovidinghis/heremailaddress.
Theusershallbeabletopostamessageonanotherusersmessagewall.
Theusershallbeabletorefreshanotherusersmessagewalltoseethenewlypostedmessages,
withoutrefreshingtherestofthecontent.
Theusershallbeabletochangehis/herpasswordwhilebeingsignedin.

NonFunctional
Oncetheapplicationisopenedforthefirsttime,itwillnotrequiretorefreshitselfduringits
lifetime.SuchapplicationsarecalledSinglePageApplicationsorSPAs.Formoreinformation
pleasecheckoutsection4:ApplicationStructure.
Usingwindow.alert()orsimilartypesofwindowbasedinputs/outputsisnotallowed.

2.TheProjectFolder
The projectfolderisanordinaryfolderthatcontainsalltherequiredfilesbuildingyourapplication.By
theendoflab1,yourprojectfolderwillcontainthefollowingfiles:

client.html//created
client.css//created
client.js//created
serverstub.js//provided

client.html
The client.html file will contain all oftheHTMLcodeimplemented by youwhich mainlyshapesthe
UI.Italsousesallother files mentionedin thelistabove.As youproceed,you willadd more HTML
codetothisfile,movingtowardsafullyfunctionalwebapplication.

Figure1Initialcontentofclient.html.
<html>
<head>
<linkhref="client.css"type="text/css"rel="stylesheet">
<scriptsrc="client.js"type="text/javascript"></script>
<scriptsrc="serverstub.js"type="text/javascript"></script>
</head>
<body>
</body>
</html>

client.js
The client.js file willcontainallthefunctionalityyou implement. Asyou proceed,youwill addmore
Javascript code to this file, moving towards a fully functional web application. Make sure that you
separatedifferentfunctionality indifferentmethods fromthebeginning,makingdifferentpiecesofthe
codeeasytouseandreuse.
Figure2Samplecodeinclient.js.
displayView=function(){
//thecoderequiredtodisplayaview

window.onload=function(){
//codethatisexecutedasthepageisloaded.
//Youshallputyourowncustomcodehere.
window.alert("HelloTDDD97!")

}
3

client.css
Thisfilewillcontainallthe styling youimplement.You willimplementthisfilecompletely from the
scratchasyouproceedstepbystep.

serverstub.js
This file simulates the serverside codefor Twidderapplicationin Javascript atclientside. There are
threereasonsbehindprovidingserverstub.js:

1. Without knowing what the serverside functionalities are, what each takes asinputand what
eachreturnsasoutput,implementingtheclientsidecannotbecompletelydone.
2. As every web application is the combination of the clientside and the serverside working
together,byhavingtheserversidein handandimplementingtheclientsidebytheendoflab1
youcanhaveafullyfunctionalapplicationinanearlystage.
3. Asserverstub.js is inJavascriptlanguageandislocatedatclientside, thereisnoneedtobe
concerned about client/server communication at current stage and you can simply use the
providedjavascriptmethodssimulatingdifferentserversidefunctionalities.

For example, the method serverstub.signUp(formData)does

sign up a user based on the


provided information.thenyoucanuseserverstub.signIn(username,password)tosign
in the same registered user. In lab 2, you will have the chanceto reimplement theserverstub.js in
python languageatserverside.Bytheendoflab 3,you willremoveserverstub.js andwill connect
your clientsideandserverside code, implementedin labs1and2,togethermakingafullyfunctional
application.
All the serverstub methods will return an object containing the fields success, message and
data.The successfieldcontainsaboolean tellingiftherequest has beensuccessful ornotandthe
message field contains an error message if something has gone wrongor asuccessmessageifthe
request has been completed successfully. The data field contains the returned data from the
serverstubifthemethodisexpected toreturnanyother data,otherwise itisundefined. You canfind
thedocumentationforthemethodsprovidedbyServerstubJSattheendofthisdocument.

3.DevelopmentTools
Tocompletethis labyouwill needatext/codeeditorandawebbrowser.Forbothcasesyouarefreeto
useanytoolofyourchoiceaslongas:
1.Thetext/codeeditorofyourchoicedoesnotprovideanyvisualwebdesigningcapability.
2. The web browser of your choice supports HTML5. We recommend Google Chrome and Mozilla
Firefox because of their good support for web development and the tools they provide. It is highly
recommended to use the Web Console and Element Inspector tools provided by both of the
browsersduringthedevelopment.

Note:usingvisualwebdesignersisnotallowed.

4.ApplicationStructure
Twidder isa SinglePage Application, whichiscomposedof twoviews(states)namedWelcome and
Profile. Depending on the user is signedin ornot,aviewisselectedanddisplayed tothe user.Only
one of the two views can be displayed at atime. Asthe user opens theclient.html file forthe first
time, theWelcome view is displayedto theuserwhichenableshim/hertosignupand/orsignintothe
system. Once the user is signedin, the Profile view is displayed, which enables the user to use the
provided applicationfunctionalities. Theuserhasthepossibilitytosignout andreturntotheWelcome
view/page.
Astheuserrefreshesthe page, thecurrent view is maintainedandtheusershall beabletocontinue
his/her work. At the same time, if the user closes the client.html page and opens it again, the
previously loaded view shallbeloadedagain andthe user can continuehis/herwork. Forexample,if
the user signsinand closesthe pagebeforesigning out,the Profile view shallbeloadedoncetheuser
reopenstheclient.html.
Figure3ThestatediagramoftheTwidderapplication.

Note:Bytheendoflab1,yourfinalproductisexpectedtobehaveaccordingly.
6

5.LabInstructions
Lab 1isdividedintoseveralstepsto helpyougetagoodworkflow.Eachstepadds anewparttothe
applicationuntilyouhaveafullyfunctionalapplicationbytheendoflab1.

Step0:Creatingtheprojectfolder
In thisstep,youarerequiredto create aprojectfolder basedontheinformationavailablein Section 2.
As a start, you need to create a folder with an appropriate name on the file system which will
accommodate all thefiles building up theTwidderapplication.AsmentionedinSection2,youneedto
create three files from scratch in the project folder and add one provided file named serverstub.js
availableonthe coursepage.client.htmlneedstohaveenoughcodetouseallotherfilesinsideofthe
project folder. client.cssandclient.jsare theonly emptyfilesfornow.Figure1 demonstrates the
initialcontentofclient.html.

Step1:Designingthewelcomeview
In thisstep,youwillcreatethesigninandsignupformsusingHTMLandCSSinatemporaryHTML
file named welcome.html, which is using a temporaryCSS file named welcome.css. The signin and
the signup forms shall be separate, and will not be providing any functionality at thecurrent stage.
Yourpageshall belaidout asdemonstratedin Figure 4.You shalluseCSS forstylingthelayoutand
usingHTMLtablesisnotallowed.
Figure4TheWelcomeviewlayout.

Thesigninformshallrequirethefollowinginformation:
1. Emailasusername
2. Password

Thesignupformshallrequirethefollowinginformation:
1.
2.
3.
4.
5.
6.
7.
8.

Emailasusername
Password
Repeatpassword
Firstname
Familyname
Gender
City
Country

Eachpieceofinformationinboth formslikeusernameorgender is requestedas asinglerowincluding


alabelandaninputelement.Eachformalsocontainsasubmitbuttonwhichappearsatthelastrow.

Note: An image containinga logoand sloganisprovidedtobeembeddedinsideofthewelcome


viewinthespecifiedarea.Youcanalsouseacustomimagetobedisplayed.

Figure5AsampleoutputoftheWelcomeview.

Step2:Displayingacertainview
The purposeof thisstepistobuildone HTMLfilefor thewhole applicationthatiscapabletodisplay
differentviewsoftheapplicationdependingonwhethertheuserissignedinornot.
Add the welcome.html content, only the HTML code which resides inside of the bodytag,

to
client.html and place it inside a <scripttype=text/view></script> tag with an
appropriate id(e.g.,

welcomeview). All scripttags

should belocatedin theheadoftheHTML


file.Thencopyallyour CSScode from welcome.csstoclient.css.From thispointwe do notneed
the welcome.html and welcome.css filesanymore. Youwill alsoneedtocreate another script
tag, which will be completed in the following steps. It should have an easily accessible id(e.g.,

profileview) and only contain an arbitrary line of text. Each of the above scripttags

contain
sufficientHTMLcodetorepresentaview.
Once the client.html document is loaded, we need to decide which view should be displayed
depending on whether the user is signedin in or not. Because there is no login mechanism
implemented yet, for now you need to display the Welcome view once client.html is opened and
loaded.

How it works?
Oncea pieceofHTMLcodeisplacedinsideof<scripttype=text/view></script>tag,

the browserskips renderingit becauseitdoesnotrecognizethetype,text/viewis
atypechosen
by us and is not known to the browser, and only adds the scripttag
to the DOM treecontaining
someunrecognized script. Depending on whichstate theapplication isin,signedinor not,thispiece
ofscriptrepresentingaviewcanbereadandinsertedtothepageoncethepageisloaded.

How to know the page is loaded?


Once the page is loaded completely by the browser and the DOM treeisbuilt, themethodonload
belonging to thewindowobject

iscalled automaticallybythe browser. Byoverloadingtheonload


method, a custom piece of code, in this case the code for readingandinserting HTMLcode,canbe
executedeverytimethepageisloadedorreloaded.

How to read and insert HTML code?


Becausethe scripttags

arepartoftheDOMtree andgiven thattheyhaveanappropriate id, they


canbeaccessedandtheircontentcan beread.Forinsertingthereadcontent,whichisapieceofHTML
code,ataglocated inthe bodyis
required,whichwillaccommodatetheread content.Adivtag
with
anappropriate idis
themostpreferableonebecauseithasbeen designedforprovidingsections.Once
the HTMLcodeisinserted, theDOMtreeisupdatedandtheaddedcontentisdisplayedautomatically.
Inotherwords,theHTMLcodeiscopiedfromascripttagandpastedinsideofadivtag.

Step3:Implementinguserinputvalidationforsigninandsignupforms
Whileperformingthe signinandsignupoperations,we prefer tominimizetheloadand trafficon/to
the server.Onewayofdoingthatisto makesurewedonotsendunnecessaryloginandsignuprequests
9

that willberejected by theserver becauseof incorrectorinadequateinformation.Inthisstep,youwill


make sure the signin andsignupformsholdvalidinformationbeforearequestissenttotheserver.
This means unless the following criteria are met, this can of course be different application to
application,norequestshallbemadewhenthesubmitbuttonisclicked:

1.
2.
3.
4.

Nofieldshallbeblank.
Theemailfieldshallcontainawellformatedemailaddress
Forsignup,bothpasswordfieldsmustcontainthesamestring.
ThepasswordisatleastXcharacterslonginbothforms.

ToimplementthevalidationmechanismyouneedtouseHTMLandJavascriptbothandimplement a
methodinsideof client.jsforeachformwhichhandlesthevalidationwhenevertheuserclicksonthe
submitbutton.

How it works?
ThankstoHTML5partofvalidation, items1 and2, canbeachieved by choosingacorrectinputtype.
Forexamplethetypeemail,maketheformdothevalidationautomaticallyandcheckifthecontentis
a well formated email address or not. You can also use the attribute required, to make a field
mandatoryornot.
Implementing items 3 and 4 takes more effort and you need to use Javascript for performing the
validation. You will use the forms onsubmit attribute ortheelements oninputeventattributeto
callyourcustomvalidatormethodbeforetheactualsubmission.

Step4:Addingthesignupmechanism
In this step you are required to add
the signup functionality by calling
serverstub.signUp(dataObject)after

thevalidationprocessissucceeded.Asmentionedin
section 2, the data passed to serverstub.signUp(dataObject)is
in form of a Javascript
objectwiththefollowingfields:

1.email
2.password
3.firstname
4.familyname
5.gender
6.city
7.country

If the user tries to register with anemailaddressthat is already registered, thisistobeshowninthe


same way as faulty fields during the validation, this time the error message returned from the
serverstubshallbedisplayed.
Ifthesignupsucceeds,themessage returnedbyserverstub.signUp(dataObject)shall

be
displayedortheusershallbedirectlydirected,loggedin,tohis/herpage.
10


Step5:Addingthesigninmechanism
In this step you are required to add
the signin functionality by calling
serverstub.signIn(username,password)after

the validationprocessissucceeded. As
mentioned in section 2, the datapassedtotheserverstub.signIn(username,password)
functionisinformoftwoseparatestringarguments:

1. Emailasusername
2. Password

To keep track of the signedin user, the serverstub uses a tokensystem. Once the
serverstub.signIn(username, password) method is called and signin process is
completed successfully, theserverstub createsarandomizedtokenandreturnsittotheclientstored in
the fielddataofthereturnedobject. Thistoken has tobestoredatclientsidetobeused further for
sendingrequeststo theserverstub. Thisshallbedone usingwebstoragefacilityaspartofHTML5.In
other words, If the user is signedin then a token exists atclientsiderepresentingthesignedinuser
otherwisethereisnosuchtokenstoredatclientside.
Asyouremember,in step 2you wererequiredto displaytheWelcomeviewasthepagewasloaded
because at thattime no signinmechanism wasin place.nowthatpartneedstobechangedanddecide
whichviewneedstobedisplayedbasedonifthereisatokenatclientsideornot.Thismeans,oncethe
page is loaded/reloaded the right view shall be displayed. The only issue is that for transiting from
Welcome viewto Profileview aftersigningin, theuserneedsto refreshthe page. Tosolvetheissue,
the deciding code should be called manually after the token is stored at clientside as it is called
automaticallyaftereachpageload/reload.
Iftheusernameorpasswordisincorrectthereturned errormessage by theservershallbedisplayedto
theuserandnotokenshallbegenerated.

Step6:Implementingatabulardatapresentation
Oncetheusersignsin, the Profile view is displayedtotheuser.Currently,thisviewcontainsnothing
but a single line of text added earlier. In this step you shallimplement arow oftabswhicheachis
associatedtoapanel.Thereshallbethreetabswiththefollowingnames:
1. Home//selectedbydefault
2. Browse
3. Account
The user can only choose one tab at a time and the associated panel with its content is displayed
consequently.

11

How it works?
To implement such tabular data presentation, you can use CSS displayproperty.

once a tab is
clicked,the displayproperty

oftheselected panelissettoblockas
othersaresettonone.Itisa
good idea to implement each panel as aseparatedivtag.
Youcanalsouseanyother techniqueof
yourchoice.

Step7:ImplementingtheAccounttab
Itisconsideredagoodpracticetochangepasswordeverynowandthen.Togivetheuserthepossibility
to change his/her password, you are to implement password change functionalityinsideofthe panel
associated to the Account tab. To do this, you need to use an appropriate method provided by
serverstub.js.
Last but not least, the user shall be able to signoutfromthe systemwhenheor she is done with
his/her session. In this step you are also required to implement this functionality insideofthepanel
associated to the Account tab by using an appropriate method provided byserverstub.js. Afterthe
userissignedout,he/sheneedstoberedirectedtotheWelcomeviewautomatically.

Step8:ImplementingtheHometab
InthisstepyouaretoimplementtheHometab.Nomatterwhatstylingithas,itneedstoincludethe
followings:
1. Thesignedinuserspersonalinformationprovidedatsignupprocessexceptthepassword.
2. Atextareaandapostbuttonwhichtheusercanusetopostmessagestohis/herownwall.
3. Alistofallpostedmessagesformingawall.
4. Abuttontoreloadonlythewallinordertoseethenewlypostedmessagesbyotherusers.
Togetitdone,youalsoneedtousethemethodsprovidedbyserverstub.js.

Step9:ImplementingtheBrowsetab
In theprevious stepyouimplemented theHome tab. Inthisstepyou aretoimplementtheBrowsetab
which enables the signedin user to view other users Home page. The Browse tab shall enable the
signedinuserto enter theemailaddressofanotheruser viaa textfield andabutton.Whensubmitted,
the found users Home page shall be displayed. The view of another users Home page shall be
functionally identicaltoyour ownHomepage.Inotherwords,thesignedinusercan viewthepersonal
informationand wall ofotherusers andatthe sametimepostmessages ontheirwalls andreloadtheir
walltoseewhetherthereisanynewpostedmessagesontheirwalls.
Togetitdone,youalsoneedtousethemethodsprovidedbyserverstub.js.

12

6.Questionsforconsideration:
1. Whydowevalidatedatabefore sendingittotheserveratclientside,asopposedtojustletting
theservervalidatedatabeforeusingit?Whatwegetandwhatwelosebyit?

2. Howsecure isthesystemusinganaccesstokentoauthenticate? Isthereanywaytocircumvent


itandgetaccesstoprivatedata?

3. What would happen if a user were topostamessage containingJavaScriptcode?Wouldthe


codebeexecuted?Howcanitopposeathreattothesystem?Whatwouldthecountermeasure?

4. What happenswhenweusetheback/forwardbuttonswhileworkingwithTwidder? Isthisthe


expectedbehaviour?Whyarewegettingthisbehaviour?Whatwouldbethesolution?

5. What happens when the user refreshes the page while working with Twidder ? Is this the
expectedbehaviour?Whyarewegettingthisbehaviour?

6. Is it a good idea to read views from the server instead of embedding them inside of the
client.html? What are the advantages and disadvantages of it comparing to the current
approach?

7. Isitagoodideato return trueorfalsetostateifanoperation has gonewrongattheserverside


ornot?Howcanitbeimproved?

8. Isitreliabletoperformdatavalidationatclientside?Ifso pleaseexplainhowandifnotwhat
wouldbethesolutiontoimproveit?

9. Whyisntitagoodideatousetablesforlayoutpurposes?Whatwouldbethereplacement?

10. How do you think Single PageApplicationscan contribute tothe futureoftheweb?Whatis


theiradvantagesanddisadvantagesfromusageanddevelopmentpointofviews?

7.PresentationandEvaluation
Onceyouare finishedwith lab1,you willpresentyourworktoyourresponsiblelabassistantduringa
scheduledlabsession.Youmaybeaskedaboutthedetailsofyourimplementationindividually.

13

Publicmethodsprovidedbyserverstub.js

serverstub.signIn(email,password)

Description:Authenticatestheusernamebytheprovidedpassword.
Input:twostringvaluesasusernameandpassword.
Returneddata:Astringvaluecontainingarandomlygeneratedaccesstokeniftheauthenticationis
successful.

serverstub.signUp(dataobject)

Description:Registersauserinthedatabase.
Input:Anobjectcontainingthefollowingfields:
email,password,firstname,familyname,gender,cityandcountry.
Returneddata:

serverstub.signOut(token)

Description:Signsoutauserfromthesystem.
Input:Astringcontainingtheaccesstokenoftheuserrequestingtosignout.
Returneddata:
serverstub.changePassword(token,oldPassword,newPassword)

Description:Changesthepasswordofthecurrentusertoanewone.
Input:
token:Astringcontainingtheaccesstokenofthecurrentuser
oldPassword:Theoldpasswordofthecurrentuser
newPassword:Thenewpassword
Returneddata:
serverstub.getUserDataByToken(token)

Description: Retrieves the stored data for the user whom the passed token is issued for. The
currentlysignedinusercanusethismethodtoretrieveallitsowninformationfromtheserverstub.
Input:Astringcontainingtheaccesstokenofthecurrentuser.
Returneddata:Auserobjectcontainingthefollowingfields:
email,firstname,familyname,gender,cityandcountry.
serverstub.getUserDataByEmail(token,email)

Description:Retrievesthestoreddatafortheuserspecifiedbythepassedemailaddress.
Input:
14

token:Astringcontainingtheaccesstokenofthecurrentuser
email:Theemailaddressoftheusertoretrievedatafor
Returneddata:Auserobjectcontainingthefollowingfields:
email,firstname,familyname,gender,cityandcountry.
serverstub.getUserMessagesByToken(token)

Description: Retrieves the stored messages for the user whomthepassedtoken is issuedfor.The
currentlysignedinusercanusethismethodtoretrieveallitsownmessagesfromtheserverstub.
Input:Astringcontainingtheaccesstokenofthecurrentuser.
Returneddata:Anarraycontainingallmessagessenttotheuser.
serverstub.getUserMessagesByEmail(token,email)

Description:Retrievesthestoredmessagesfortheuserspecifiedbythepassedemailaddress.
Input:
token:Astringcontainingtheaccesstokenofthecurrentuser
email:Theemailaddressoftheusertoretrievemessagesfor
Returneddata:Anarraycontainingallmessagessenttotheuser.
serverstub.postMessage(token,message,email)

Description:Triestopostamessagetothewalloftheuserspecifiedbytheemailaddress.
Input:
token:Astringcontainingtheaccesstokenofthecurrentuser
message:Themessagetopost
email:Theemailaddressoftherecipient
Returneddata:

15

Anda mungkin juga menyukai