library.kre.dp.ua kurs/Програмування + мови... · contents preface 1 introduction...

Post on 03-Oct-2020

18 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

BuildWebApplications

with

Java

Learneveryaspecttobuildwebapplicationsfromscratch

YousufBaig

BuildWebApplicationswithJavaCopyright©2015MirzaYousufAhmedBaig

Allrightsreserved.Nopartofthisbookmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorbyanymeans,withoutthepriorwrittenpermissionofthepublisher.

InlovingmemoryofmymotherlateAneesAyesha

CONTENTS

PREFACE

1INTRODUCTION

Whatarewebuilding?

Whyarewebuilding?

Howarewebuilding?

TheOutline

Step1:ComposeRequirementsSpecifications.

Step2:CreatePrototypeoftheApplication.

Step3:BlueprinttheArchitectureandHighLevelDesign.

Step4:DesigntheDatabase.

Step5:BuildtheJavaFramework.

Step6:BuildtheSharedComponents.

Step7:BuildtheIndividualUseCases.

Step8:Testing.

Step9:Deployment.

2PREPARINGTHEENVIRONMENT

HardwareRequirements

SoftwareRequirements

InstallingOracleXEDatabase

InstallingOraclejdeveloper11g

InstallingApacheTomcat8

3SDLC,OOADANDUML

SoftwareDevelopmentLifeCycle(SDLC)

ObjectOrientedAnalysisandDesign(OOAD)

UnifiedModelingLanguage(UML)

UseCaseDiagram

ClassDiagram

SequenceDiagram

ActivityDiagram

4REQUIREMENTS

TheRequirementsPhase

RequirementsSpecifications

ApplicationTitle

ExecutiveSummary

DetailedRequirementsSpecification

AuthenticationandAuthorizationModule

R1:TheAuthentication.

R2:TheAuthorization.

TheStudentModule

R3:LoadStudent.

R4:UniqueStudentIdentifier.

R5:StudentDetails.

R6:StudentAcademics.

ScholasticPerformance-CoreCurriculum-Assessment

Co–ScholasticActivities

ScholasticPerformance-CoCurriculum-Assessment

SynthesisandRecommendations

R7:ShowStudentAttendance.

R8:StudentFees.

TheAdministrationModule

R9:ManageStudentAttendance.

R10:AddStudent.

R11:ReportbyClass.

ReportCriteria

ReportResults

TheHelpandMiscellaneousModule

R12:HelpPages.

R13:HeaderandFooter.

R14:TheMenu.

5PROTOTYPING

Pagelayoutandtemplate

Prototype1:LoginPage.

Prototype2:Dashboard/HomePage.

Prototype3:LoadStudent.

Prototype4:StudentDetailsPage.

Prototype5:StudentResultsPageforSemester1.

Prototype5:StudentResultsPageforSemester2.

Prototype6:StudentAttendancePageforSemester1.

Prototype6:StudentAttendancePageforSemester2.

Prototype7:FeesStatusPage.

Prototype8:ManageAttendancePage.

Prototype9:AddStudentPage.

Prototype10:Reportbyclasspagewithreportcriteriaoptions.

Prototype10:Reportbyclasspagewithreportdata.

Prototype11:Helppages,resultslegendpage.

6THECLIENTSIDE

JavaScript

BisScript.js

CascadedStyleSheet

BISStyle.css

7THEPATTERNS

ArchitecturalPatterns

MVC

DesignPatterns

CommandPattern

FrontControllerDesignPatten

ValueObjectDesignPattern

8THEARCHITECTURE

TheBIS-SMSApplicationArchitecture

9DATABASEDESIGN

BisSecurityRealmSchema

UsersTable

UserRolesTable

BisSchema

StudentDetailsTable

ParentDetailsTable

EmployeeDetailsTable

TransportationDetailsTable

ClassTeacherMappingTable

StudentAttendanceTable

StudentFeesTable

ScholasticResults/CoScholasticResultsTables

BISConstantsTable

10THEFRAMEWORK

TheMVCBasedJavaFramework

ViewLayer

ModelLayer

ControllerLayer

BisFramework

TheBisFrameworkArchitecture

ClientTier

DatabaseTier

WebServerTier

ViewLayer

ControllerLayer

ModelLayer

CommandProcessor

TheControlFlow

11THELOGGING

Whatisloggingandwhyitisneeded?

LoggingLevels

UsingLog4jinjdeveloper

Thelog4j.propertiesfile

12SESSIONMANAGEMENT

UnderstandingSession

LeveragingHttpSession

13INTERACTINGWITHTHEDATABASE

Theapproachesfordatabaseconnectivity

UsingDataSources

14THEBIS-SMSPROJECTCOMPONENTS

JavaServlets

ControllerServlet.java

AjaxControllerServlet.java

TheCommandProcessors

BisCP.java

BisCommand.java

TheServiceClasses

BisService.java

TheJavaBeans

StudentBean.java

BisBean.java

TheUtilityClasses

Bisutility.java

DatabaseService.java

BisConstants.java

TheJavaServerPages

BisHome.jsp

Log4j

15IMPLEMENTINGUSECASES

UseCase:Authentication.

BisLogin.jsp

UseCase:Authorization.

BisDashboard.jsp

BisHome.jsp

UseCase:LoadStudent.

LoadStudentCP.java

StudentDetailsService.java

BisDashboard.jsp

BisScript.js

UseCase:Getstudentdetails.

GetStudentDetailsCP.java

StudentDetailsService.java

StudentDetailsBean.java

StudentDetails.jsp

UseCase:Getstudentattendance.

GetStudentAttendanceCP.java

StudentAttendanceService.java

StudentAttendanceBean.java

StudentAttendance.jsp

UseCase:Getstudentfees.

GetStudentFeesCP.java

StudentFeesService.java

StudentFeesBean.java

StudentFees.jsp

UseCase:Getstudentresults.

GetStudentAcademicsCP.java

StudentAcademicsService.java

StudentResultsBean.java

StudentAcademics.jsp

UseCase:Helppages.

ResultsLegend.html

UseCase:Reportbyclass.

GetReportByClassCP.java

ReportByClassService.java

ReportByClassBean.java

ReportByClass.jsp

UseCase:AddStudent.

AddStudentCP.java

AddStudentService.java

StudentDetailsBean.java

AddStudent.jsp

UseCase:ManageStudentAttendance.

ManageAttendanceCP.java

StudentAttendanceService.java

StudentAttendanceBean.java

ManageAttendance.jsp

16SECURINGAPPLICATION

ConfiguringdatasourcesecurityrealmforApacheTomcat8

EnablingSecurityforBIS-SMS

BIS-SMSUsersandRoles

17BUILDANDDEPLOYMENT

TheWebApplicationArchive

BuildingtheBis.warfile

Deployingthe.warfile

DeployingBis.wartoApacheTomcat

18TESTING

UnitTesting

SystemTesting

UserAcceptanceTesting(UAT)

19DEBUGGING

Whatisabug?

Stepstoresolveabug

Describethebug

Reproducethebug

Diagnosisandresolution

Verifyingthefix

Applyingthepatch

20OTHERIMPORTANTTOPICS

AJAX

Performancetuningandbestpractices

Scalability

21IMPORTANTFILES

web.xml

Context.xml

22APPENDIX

Databasescripts

Schema:BisSecurityRealm

Schema:bis

PREFACE

Softwareengineeringisaveryvastandcomplexfiled.Therearemanyprogramminglanguages,technologies,platforms,frameworksandmethodologiesavailabletobuildthesoftwaresolutions.Tobuildsoftwaresolutionsateamwithvariousrolesisrequired.Eachmemberoftheteamisrequiredtohaveskillsandexperienceforaparticularroleandresponsibilities.Fortechnicalroleslikedeveloper,technicalleadandsolutionsarchitecttheumbrellaoftechnicalskillsrequirementisvast.Suchrolesdemandknowledge,skillsandunderstandingofprogramminglanguage,frameworks,patternsandothertechnologies.

ThemostpopularprogramminglanguageforbuildingwebbasedapplicationsisJava.Javaprovidesthestandardeditionwithprovidesthecoreobjectorientedprogramminglanguagecapabilities.Italsoprovidestheenterpriseeditionusingwhichenterpriseapplicationscanbebuilt.TherearemanyopensourceandpaidframeworksavailableinthemarketbuiltusingJava.Theseframeworksprovideanoptiontoquicklybuildwebandenterpriseapplications.ThepopularframeworksforbuildingwebapplicationusingJavaprovidelotsofreusablecomponentsandmanyconfigurablesolutionsthathelporganizationssavetime,moneyandeffort.

TobesuccessfulonatechnicalroleinanorganizationortobuildwebapplicationsusingJavaasanindependentfreelancerortostartacareerinJavaasawebprogrammer/developeritdemands:

TohaveexpertiseknowledgeonJavaprogramminglanguage.HandsonexperienceonormorepopularframeworkslikeSpring,StrutsandOracleADF.Atleastintermediateskilllevelofpl/sqlandpopulardatabaseslikeOracleandDB2.KnowledgeofwebtiertechnologieslikeServlet,JSPs,HTML,CSSandJavaScript.Knowledgeofwebserver,servletcontainersandapplicationservers.Fundamentalknowledgeofvarioussecuritythreatsandtheirsolutions.

That’stheminimumlistofrequirementforskills,experienceandknowledgebesidesthelogicalability,intelligencequotientandotherhumanintellectualparameters.

TherearemanygoodbooksavailableinthemarketwhichindependentlyteachJava,WebServers,MVCbasedFrameworks,JSP,PL/SQL,AJAX,JavaScript,CSS,HTML5,UML,SDLCetc.Thisbookcoversallofthesethingsplusotheraspectstogetherwhilebuildinganactualwebapplicationfrominceptiontillcompletion.Thisbookstakesasamplewebapplicationandbuildsitfromscratch.Eachaspectisexplainedatmicrolevelwithrealtimeexamplesalongwiththeumldiagramsandcode.Thefundamentalconceptsofsoftwareengineeringandprogrammingwebapplicationsarecoveredwithhighimportance.Togetmaximumbenefitoutofthisbook,itisstronglyrecommendedtobuildthesamplewebapplicationwhilegoingthroughthebook.

Objective

Theobjectiveofthisbookistoteachbuildingmoderndaybusinesswebapplicationsusingjavaandotherrelatedtechnologies.Thisbookteacheseverythingindetailsandinsimplerwayaboutbuildingwebapplicationswithmediumtohighlevelofcomplexity.Thisbookalsocoversvarioussoftwareengineeringconceptsthatarerequiredforbuildingsoftwaresolutions.

Thebooktakesyouthrougheachandeverystepofbuildingawebapplicationfromscratch.Theobjectiveistoteachthereadereverysingleaspectofsoftwareengineeringrequiredforbuildingwebapplicationsfrominceptiontilldeploymentandsupport.Inordertoachievetheobjective,areallifebusinessrequirementistakenandthesampleprojectisbuiltstepbystepfromrequirementsgatheringtilldeploymentandsupport.

ThebookincludesbuildingalightweightMVCbasedJavaframeworkandbuildingthesamplewebapplicationusingit.Duringthecoursearchitecture,SDLC,UML,security,ajax,variouspatterns,bestpracticesandotherrelatedtopicsareexplained.

Prerequisite

BeginnerslevelknowledgeofJavaprogramminglanguage,databaseandwebrelatedtechnologiesisrequired.

Audience

AnyonewhowantstolearnbuildingwebapplicationswithJavaprogramminglanguage.Thisbookisprimarilyintendedforbeginnerswhowantstolearnvarious

aspectsofsoftwareengineeringandbuildingwebapplicationsusingJavaprogramminglanguage.Thisbookisnotlimitedforthesaidaudience,itcanbeusedforreferencebythearchitects,projectmanagersandotherstakeholderswhoareinvolvedinawebbasedapplicationproject.

Disclaimer

TheobjectiveofthisbookistoonlyteachthereaderthevariousaspectsofbuildingwebapplicationsusingJavaandrelatedtechnologies.Thesampleapplicationthatisbuildasapartoflearningisnotmeantforanyrealbusinesspurposeinasiscondition.Neithertheauthornorthepublisherholdsanyresponsibilityorlegalliabilityinanysuchcase.

Errors

Thougheverycareistakentomakesurethatthecontentofthebookisofhighestquality.Yet,humanerrorsandmistakesdohappen.Inanysuchcase,pleasenotifytheauthoratyousuf.baig@gmail.com.Thiswillhelptheauthorinfixinganyslippederrorsormistakes.

QuestionsandFeedback

Theauthorisavailableonmostofthepopularsocialnetworkingsitesincludingfacebook,linkedinandtwitter.Incaseofanyquestionsorfeedback,theauthorcanalsobecontactedatyousuf.baig@gmail.com.

Acknowledgements

First,thankstomyparentsforeverything.Thankstomywifeforherloveandsupportformyfirstbookproject.ManythankstomysisterNaziaMerajandfriendShoukatAliforalwaysbeingthereforme.Specialthankstomycolleaguesandfriendsforencouragingandsupportingthisbookproject.Thanksformotivatingmeandhelpingmewiththesuggestionsandreviews.BigthankstomychildrenMyiesha,ZainandZaidfortheirloveandforbeingmyinspirationinlife.

1INTRODUCTION

Whatarewebuilding?

Throughoutthebookwewillbebuildingawebbasedstudentmanagementsystem(SMS)forahypotheticalschoolcalled“BaigInternationalSchool”(BIS).ThesamplewebapplicationisabbreviatedasBIS-SMS.

Whyarewebuilding?

Thebestwaytolearnanythingistogetthehandsdirty.Whenadeveloperstartsbuildinganysoftwaresolution,he/shegetslotsofdoubtsandquestionswhileactuallydoingit.WearebuildingthesampleBIS-SMSwebapplicationinordertolearnvariousaspectsofbuildingwebapplicationsfromscratch.Whenthereaderarchitects,designsanddoesthecodinghandson,thereaderlearnseveryaspectpractically.Whenthereaderbuildstheworkingapplicationstepbystep,theconfidenceofthereaderasadeveloperisboosted.

Howarewebuilding?

WearebuildingtheBIS-SMSwebapplicationfollowingthewaterfallsoftwaredevelopmentlifecycle(SDLC)model.Theapproachforbuildingtheapplicationusingthismodelisdetailedintheoutlinebelow.

TheOutline

Hereistheoutlineofthesamplewebapplicationwewillbebuilding.Wewillfollowwaterfallmodelforthedevelopmentofsampleapplication.Hence,thebelowmentionedstepswillstrictlygoinorder.For.e.g.step3willnotbetouchedbeforecompletionofstep2whichinturnisdependentonstep1.

Step1:ComposeRequirementsSpecifications.Herewewillpendownwhattheapplicationwillprovideindetail.Thiswillalsodraw

thescopeofourproject.Therequirementsspecificationsneedstobeclear,conciseand

specific.

Step2:CreatePrototypeoftheApplication.HerewewillcreateplainHTMLpagesforeachwebpageoftheBIS-SMSapplication.

Wewillalsoaddnavigationlinksbetweenpages.Thisshouldclearlydemonstratehowtheapplicationwilllooklikeandhowitwillbehaveuponuserinteraction.Inshort,thisisreferredtoasUI(userinterface)andUX(userexperience).Thisshouldvirtuallyrepresentthecompleteapplicationwitheverysinglepageandfunctionalitymockedupintheprototype.

Step3:BlueprinttheArchitectureandHighLevelDesign.

Herewewillcreatethearielviewoftheapplication.Thiswillshowcasethebiggerpicturewhichprovidesthequickunderstandingoffunctionalities,distributionandinteractionofvariousmodules,tiersandtechnologies.Thebestanalogyisahousebuildingplanwhichshowcasesthenumberofrooms,livingarea,utilitiesetc.Theoutcomeofthisexercisewillbethesoftwarearchitecturediagramwithdetailsofeachentityinit.

Step4:DesigntheDatabase.

Thisisoneofthemostimportantactivity.Thedatabasedesignhastobedoneverydiligentlylivingzero(ideally)orminimumscopeforchangesormodificationinthefuture.Achangeindatabaseentitiesliketableswillhaverippleeffectonthedesignandcode.Foranexampleaddingorremovingacolumninoneofthetablepostcodingwillhaveimpacteverywhere,potentiallythedatabasequeriesmaybreak.

Step5:BuildtheJavaFramework.

WewillbebuildingourownlightweightMVCbasedframework.Oncetheframeworkisready,itwillhelpusfocusingmoreonimplementingbusinesslogicforindividualusecases.Theframeworkwillprovideusallthebasicservices.Remember,theframeworkwewillbebuildingisreusable.Thesamecanbeusedtobuildotherwebapplications.

Step6:BuildtheSharedComponents.

Wewillidentifyandbuildallthesharedcomponents.Sharedcomponentsarethereusablecomponentswhichwillbeusedthroughouttheapplication.Utilityclassesarethebestexampleforsharedcomponents.Forexampleautilityclassforgettingandreleasingdatabaseconnectioncanbebuiltbeforetheactualusecasesimplementation.Togetadatabaseconnection,wewillonlybeimportingthisclassandmakingamethodcallwhichreturnsusadatabaseconnection.

Step7:BuildtheIndividualUseCases.

Wewilllistdownalltheusecasesandstartbuildonebyone.Eachusecasewillleveragetheframeworkandthesharedlibrariestoachievethebusinesslogicitrequires.Herewewilldetailtheobjective,flowandstateofvariousentitiesviavariousdiagrams.Thiswillserveaslowleveldesign.Thishastobeveryclearandcomplete.Lookingatthelowleveldesignthedevelopershouldbeabletocodetheusecase.

Step8:Testing.

Wewillfinallytesttheapplicationfromendtoend.Thisisreferredtoassystemtestingwherewewillintegrateandtestalltheusecases.Wewillalsotestalltheusecasesindividuallybeforeintegration,thisiscalledunittesting.Postintegration,thewholeapplicationwillbehaveassinglesystemfortheenduser.Thistestingwillshowustheendusersperspective.ThisisreferredtoasUserAcceptanceTesting(UAT).Wewillperformunittesting,moduletesting,systemtestingandUATintheordermentioned.

Step9:Deployment.

Thisisthefinalstepwherewewillbundletheapplicationanddeployittotheserver.Herewewillbuildanddeployourapplicationtotheserver.PriortodeploymentweneedtocreatedependencieslikeDataSourcesontheserver.Wewillcreatesuchartifactsbeforedeployment.Wewillalsoseevariousoptionsavailabletobuildanddeployourapplicationtotheserver.

2PREPARINGTHEENVIRONMENT

Inthischapterwewillcreatethedesigntimeandruntimeenvironmentwhichwillbeusedtobuildanddeploythesampleapplication.Belowisthelistofhardwareandsoftwarerequirements.

HardwareRequirements

Alaptoporadesktopwiththefollowingminimumconfigurationisrecommended.

Processor:i3orhigher

RAM:4GbMinimum

SoftwareRequirements

Inordertobuildanddeploythesampleapplication,weneedtoinstallthefollowingsoftware.

OperationSystem:AnyUNIXflavororwindowsOS.However,windowsisstronglyrecommendedasthebookexplainsbuildingthesampleapplicationonwindows7OSspecifically.InstallingOSisoutsidethescopeofthisbook.IfnonwindowsOSisused,theinstallationinstructionsfortheparticularOSneedstobefollowed.Ensurethatthesetup/installationisavailablefortheOSused.Itmayberequiredtodownloadadifferentversionofthesetup/installationfilesbasedontheOSandversion.

Database:OracleXE10g.

WebServer:ApacheTomcat8isusedfordeployingtheapplication.Thisprovidesboththewebserveraswellastheservletcontainer.

IDE:Oraclejdeveloper11gistheintegrateddevelopmentenvironment(IDE)usedfordevelopingtheapplication.

LetsgetstartedwiththeinstallationofOracleXEdatabase,Oraclejdeveloper11gandApacheTomcat8server.Notethat,alltheinstallationinstructionsbelowappliestoWindows7OS.Forotheroperatingsystems,theinstallationinstructionsmaydiffer.

InstallingOracleXEDatabase

Step1:DownloadOracleXE10gsetupfilefrom:http://www.oracle.com/technology/products/database/xeforwindows.

Step2:Logontowindowswithauserthathasadministrativeprivileges.RightclickOracleXE.exefileandclickrunasadministrator.Thiswilllaunchtheinstallerasshowninthefigurebelow.

Step3:Clicknextontheinstallwizardwelcomewindow.

Step4:YouwillbepromptedwithLicenseAgreementdetails.Select“IAccept”andclicknext.

Step5:MakesurethatOracleDatabase10gExpressEditionisselected.Specifyadestinationfolderforthedatabaseinstallationandclicknext.

Step6:SpecifythepasswordforSYSandSYSTEMaccountsandclicknext.Notethat

thispasswordisrequiredinlaterstagesforadministeringthedatabase.

Step7:Theinstallationsummarypageisdisplayed.Clickinstalltoproceed.

Step8:Thewizarddisplaystheconfirmationforthecompletionoftheinstallation.KeeptheLaunchtheDatabasehomepageoptioncheckedandclickfinish.

Step9:Thiswilllaunchthebrowserwiththehomepageofthedatabasejustinstalled.Entersysorsystemuserwiththepasswordtologin.Uponsuccessfullogin,thefollowingpageisdisplayed.

ThisconcludestheinstallationofOracleXE10gdatabase.

InstallingOraclejdeveloper11g

Step1:DownloadtheinstallerforOraclejdeveloper11gfrom:

http://www.oracle.com/technetwork/developer-tools/jdev/downloads/index.html

Step2:Logontowindowswithauserthathasadministrativeprivileges.Rightclickjdevstudio11123install.exefileandclickrunasadministrator.

Step3:Thiswilllaunchtheinstaller.Clicknexttoproceed.

Step4:Select“CreateanewMiddlewareHome”radioandspecifyahomedirectoryfortheoraclemiddleware.ThisistherootdirectorywherealltheOracleMiddleware

softwarewillbeinstalled.Clicknexttoproceed.

Step5:SelectTypical.Thiswillinstalljdeveloper,ADFandWeblogicServer.Clicknexttoproceed.

Step6:Theinstallerwilldisplaytheinstallationdirectoriesfortheserverandide.Acceptthedefault.Justclicknextonthisscreenandproceedfurther.

Step7:SelectAllUsersandclicknext.

Step8:Verifythattheinstallationsummaryincludesjdeveloperandadf,WeblogicServerandJDK.Clicknexttoproceed.

Step9:Thiswillstarttheinstallation.

Step10:UnselectRunQuickstartandclickdonetofinishtheinstallation.

Step11:GotostartmenuandclickJDeveloperStudio.ThiswilllaunchOraclejdeveloper.

ThisconcludestheinstallationofOraclejdeveloper11g.

InstallingApacheTomcat8

Step1:DownloadthezipinstallerfileforApacheTomcat8from:

https://tomcat.apache.org/download-80.cgi

Step2:Unzipthefileapache-tomcat-8.0.21-windows-x64.zipfiletoalocalfolder.

Step3:ApacheTomcat8.0requiresaJavaStandardEditionRuntimeEnvironment(JRE)version7orlater.IfyoursystemhasaJREversionbelowthisorifyoursystemdoesnothaveJREitself,pleaseinstallJRE7orlaterbeforeproceedingfurther.

WeneedthefollowingenvironmentvariablesforstartingtheApacheTomcat8.0server:JRE_HOMEandCATALINA_HOME.

TheCATALINA_HOMEenvironmentvariableshouldbesettothelocationoftherootdirectoryofthe“binary”distributionofTomcat.IftherootdirectoryisoftheinstallationisE:\apache-tomcat-8\apache-tomcat-8.0.21thentheCATALINA_HOMEenvironmentvariablemustbesettoE:\apache-tomcat-8\apache-tomcat-8.0.21.

TocreatetheCATALINA_HOMEenvironmentvariablegotostart-rightclickonComputer-Selectproperties-ThiswillopenControlPanel-SystemandSecurity-System-ClickAdvancedsystemsettingsonthelefthandside.ThiswillopenuptheSystemPropertieswindow.ClickonEnvironmentVariable.ThatwillinturnopentheEnvironmentVariableswindow.Thefollowingpictureshowcasesallthesewindows.

ClicknewandaddvariablenameasCATALINA_HOMEandvariablevaluemustbethehomedirectoryoftheApacheTomcatserverasshowninthefigurebelow.

ClickOKtocloseallthewindows.

SimilarlycreatetheJRE_HOMEenvironmentvariable.ThevariablenamemustbeJRE_HOMEandthevariablevaluemustbethedirectorylocationoftheJRE(whichhasthebinfolderinit)asshowninthefigurebelow.

ClickOKtocloseallthewindows.

Step4:Gotothebinfolderandrunthestartupbatchfile.Thiswillstarttheapachetomcat8server.

Step5:Launchthebrowserandgotothefollowingurl:http://localhost:80.Thedatabaseisalreadyusingport8080.Hence,wewillchangethehttpportto80forApacheTomcat8server.

Tochangethehttpportfromdefault8080to80:

GotoconffolderintheApacheTomcatinstallationdirectory.Opentheserver.xmlfiletoedit.Locatethistag<Connectorport=“8080”protocol=“HTTP/1.1”

connectionTimeout=“20000”redirectPort=“8443”/>andchangethevalueforportfrom8080to80.Savethefileandrestarttheserver.TheApacheTomcat8serverwillnowlistenforhttprequestsonport80.

Iftheinstallationissuccessful,thehomepageofApacheTomcatserverwillbedisplayed.

ThisconcludestheinstallationofApacheTomcat8server.Pleasereferthesection”ConfiguringdatasourcesecurityrealmforApacheTomcat”inchapter16SecuringApplicationtoconfiguresecurityrealmforthisApacheTomcat8serverinstallation.

3

SDLC,OOADANDUML

SoftwareDevelopmentLifeCycle(SDLC)

Fromtheveryfirstthoughtofhavingasoftwaresolutionforasituationtilltheactualdeploymentofthesoftware,thesoftwaredevelopmentgoesthroughvariousphases.ThesephasesformthebuildingblocksofSDLC.Someofthesephasesareinterdependentoneachother,whilesomeareprerequisiteforothers.Someofthemcanbedoneinparallelwhileothersmaydemandaparticularorder.

Variousapproachescanbetakentobuildasoftwaresolutionfromitsinceptiontillitscompletion.TheseapproachesarereferredtoasSDLCmethodologies.Wewillnotgointodetailsofthesevariousmethodologies.WewillonlyfocusontheSDLCmethodologywhichwewillbefollowingtobuildoursampleapplication.

TheSDLCmethodologywewillbefollowingiscalledwaterfallmodel.Inthismethodology,eachphaseofSDLCgoesinaparticularsequence.ThemajortangiblephasesofwaterfallSDLCarerequirementsanalysis,design,implementation(coding),testingandmaintenance.Inwaterfallmodel,eachphasehasstrictdependencyonthepreviousphase(s).For.e.g.thedesigncannotbestartedbeforetherequirementsarefinalized.Inwaterfallmodel,thefollowingorderforSDLCisfollowed.

1. RequirementsAnalysis2. Design3. Implementation4. Testing5. Deployment6. Maintenance

Theoutlinesectioninchapteronedescribeswaterfallmodelapproachforthesampleapplicationwearebuilding.

ObjectOrientedAnalysisandDesign(OOAD)

WeareusingJavatobuildthesamplewebapplication.Javaisanobjectorientedprogramminglanguageandhencewewillbedealingwithmanyobjectsinthesampleapplication.

OOADisprimarilyidentifyingtheobjectsandtheirinteractiontoachieveourgoal.AsapartofOOADanalysisanddesignwewillcomeupwithvariousclassesandinterfacesinthecomingchapters.Foreachusecase,wewillseewhatobjectsarerequiredandwhatinteractionsarerequired.ThesewillbedepictedwithsubjectiveUMLdiagramsincludingandnotlimitedtoclassdiagrams,sequencediagramsandactivitydiagrams.

Thebottomlineis,everythingisanobjectinJava.Tousetheseobjectsatruntime,wecreateclasseswithfieldsandmethods.Hence,OOADinourcasedrillsdowntoplanningandcomingupwithJavaclassesandinterfacesandtheirinteractionstoachieveourrequirements.

UnifiedModelingLanguage(UML)

UMLisapopularmodelinglanguage.Itenablesthepictorialdepictionofvariousentities,interactionsandactivitiesthroughoutthedevelopmentlifecycle.UMLprovidesvarioustypesofdiagramswhichhelpinunderstanding,developingandrefiningthesystembeingbuilt.InthecomingchapterswewillbeusingvariousUMLdiagramsforbuildingthesamplewebapplication.Here’saquickintroofvariousUMLdiagramsusedinthisbook.

UseCaseDiagram

Ausecasediagramisavisualrepresentationofauser’sinteractionwithasystem.Thesecanbedifferenttypesofusersofasystemandalsotherecanbedifferenttypesofusecasesforagivenuser.Ausecasepictoriallydepictstheinteractionofauserwithaspecificrolewiththesystem.

ClassDiagram

Theclassdiagramisastaticdiagramanditdescribestheattributesand

operationsofaclass.Classdiagramsshowcasealltheclasses,interfaces,associations,collaborationsandconstraintsintheapplication.Thesediagramsgiveavisualrepresentationoftheclasses,interfacesandtheirrelationshipsbelongingtoaparticularsystem.

SequenceDiagram

Asthenamesuggests,sequencediagramspictoriallydepictthesequenceofoperationsperformedinaparticularordertoachieveatask.Theydepicttheflowofvariousactivitiesinasequence.Sequencediagramsarebasicallyinteractiondiagramswhichdepicttheorderandinteractionsbetweenvarioussoftwareentities.

ActivityDiagram

Activitydiagramsdepictthebiggerpictureofasystem.Theydescribetheflowfromoneactivitytoanotherandtheirconditions.Activitydiagramsarecommonlyusedtodepictthealgorithms.Thesearebehavioraldiagramsandhaveafinitenumberofsteps,conditionsandflows.

VariousumldiagramsareusedthroughoutthisbookservingtheverypurposeofUMLtounderstandthingswithmoreclarity.

4REQUIREMENTS

TheRequirementsPhase

Thisisthefirstthinginanyproject.Theclientwhowantsasystemtobebuiltcomesupwithadocumentcalledrequirements.Thisdocumentdetailswhatexactlytheclientwants.Thevendorwhoisbuildingthesystemanalyzesthisdocumentandgoesbacktotheclientwithquestions.Theclientprovidesanswersandclarificationforthevendor’squeriesandambiguities.Thisphaseisknownasrequirementsanalysisphaseoftheproject.Theoutcomeofrequirementsanalysisphaseisarequirementsspecificationdocument.

RequirementsSpecifications

Toputitsimple,requirementsspecificationdetailswhatneedstobebuiltveryspecificallyandclearlywithoutanyambiguity.Requirementsspecificationsisconcise,specific,straightforward,detailed,clearandcomplete.Requirementsspecificationshavetobeclear,detailedenoughandspecificwithoutanyambiguity.Itincludesdetailedspecificationsoftherequirementsforthesystemtobebuilt.Thisisgenerallyalegallyliabledocument.

Fortheclient,therequirementsspecificationiswhatexactlytheywant.Fortheimplementers,therequirementsspecificationiswhattheyaregoingtobuild.

Letustakeanexamplehere:Apersongoestoatailorforstitchingashirt.Heprovidestherequirementsbysayingsomethinglikethis:Ineedashirtwhichneedstobefullsleeved,whitebuttons,widenecketc.Thetailorgetsspecific,hepullsuphismeasurementtapeandpensdownthe“requirementsspecifications”like40.5inchshoulder,18inchneck,32inchlength,roundwhitebuttonsetc.

Letusnowpendowntherequirementsspecificationforthesamplewebapplicationwearebuilding.

ApplicationTitleBaigInternationalSchoolOnlineStudentManagementSystemabbreviatedasBIS-SMS.

ExecutiveSummary

Theonlinestudentmanagementsystemprovidesawebbasedsolutionformanagementofstudent’sinformation.Thissolutionisaimedforstudentsstudyinginaparticularschoolfrom1stgradeto10thgrade.Thevarioususersofthisapplicationarestudents,teachers,non-teachingstaffandschoolmanagement.Thesolutionservesasasinglesourceofinformationforallthestudentsofagivenschool.Theinformationaboutastudentincludestudent’spersonaldetails,parent’sdetails,attendance,results,performance,healthandotherattributesofastudent.

Thesolutionalsoprovidesreports,contactinformationforvariousnon-teachingstaff,chartsforstudent’sacademicandnon-academicperformancesandattendance.

DetailedRequirementsSpecification

TheOnlineStudentManagementSystemapplicationisdividedintofollowingmodules.AuthenticationandAuthorization

Student

Admin

Reports

Help

Miscellaneous

AuthenticationandAuthorizationModule

Thefollowingrequirementsfallunderthismodule.

R1:TheAuthentication.

Thesystemshallprovideamechanismtoauthenticatetheuser.Uponfirstrequesttotheapplication,theapplicationmustredirecttheusertoaloginpage.

Oncetheusersubmitstheuseridandpassword,thesystemshallperformauthentication.Iftheuseridandthepassworddoesnotmatchortheuserdoesnotexist,

thesystemshallprovideanappropriatemessageandtaketheuserbacktotheloginpage.

Iftheuserisvalidandprovidesvalidpassword,theauthenticatedusermustbetakentothedashboardpage.

R2:TheAuthorization.

Thesystemshallprovideamechanismtoauthorizetheuserbasedonarole.Themenusandthedashboardshouldberenderedbasedontheroleoftheuser.Onlythoselinksshallbedisplayedwhichtherolehasprivilege.Theuserprivilegesandtheroleshallbeasperthefollowingtable.

TheStudentModuleThismodulemustprovidethefollowingfunctionalrequirements.

R3:LoadStudent.

Thesystemshallallowtheusertoloadastudentbasedonhis/herstudentId.Thesystemshallhaveclientsidevalidationsforstudentidwithappropriateerrormessages.

R4:UniqueStudentIdentifier.

Onthepageswhereeverapplicable,thesystemshalldisplaythestudentname,semester,class,sectionandstudentidasauniqueidentifierforagivenstudentandthatshouldbereferredtoas“studentincontext”.Thisshallbedisplayedincenteredpositionjustbelowthemenus.Thisshallserveasanidentificationofastudentinquestion.Thisstudentincontextstripmustbedisplayedforallthestudentrelatedpagesonceloadstudentactivityisperformedbytheuser.

R5:StudentDetails.

Prerequisite:Thestudenthastobeloadedintocontextfirst.

Thesystemshalldisplaythefollowinginformationforagivenstudentinasinglepageview.

Student Parents Bus

StudentId Father BusId

Name Mother Driver

Gender Father’smobile Driver’smobile

Dateofbirth Mother’smobile Helper

Grade Address Helper’smobile

Section Busnumber

Classteacher Transportationtype

Height

Weight

Bloodgroup

R6:StudentAcademics.

Prerequisite:Thestudenthastobeloadedintocontextfirst.

Foragivensemesterandstudent,thesystemshalldisplaytheacademicresultsinformationasperthetablesbelow.

ScholasticPerformance-CoreCurriculum-Assessment

Thesystemshalldisplaythegradesforthefollowingsubjects:English,Mathematics,Science,SocialScience,ComputerScience,LanguageIIandLanguageIII.

ThegradesshallbeA,BandC.

SubjectvisegradesforagivenSemesterandRemarksoptionunderthetableheading“ScholasticPerformance-CoreCurriculum–Assessment”.

Co–ScholasticActivities

Foragivensemesterandstudent,thesystemshalldisplaythefollowingacademicsinformation.

SubjectvisegradesforCriticalThinking,CreativeThinking,CollaborativeLearning,CommunicationSkill,ComprehensiveGrowth,IntelligenceQuotient,EmotionalQuotient,SocialQuotient,HealthQuotientandCommunityConsciousnessunderthetableheading“Co–ScholasticActivities”.ThegradesshallbeLatent,Developing,EmergingandOutstanding.

ScholasticPerformance-CoCurriculum-Assessment

Foragivensemesterandstudent,thesystemshalldisplaythefollowingacademics

information.

Thesystemshalldisplaythegradesforthefollowingsubjects:Arts,Music,Dance,PhysicalEducation,ValueEducationandSchoolProject.ThegradesshallbeA,BandC.

SubjectvisegradesforagivenSemesterandRemarksoptionunderthetableheading“ScholasticPerformance-CoCurriculum–Assessment”.

SynthesisandRecommendations

Foragivensemesterandstudent,thesystemshalldisplaythefollowingacademicsinformation.ScholasticPerformanceandCo–ScholasticPerformanceunderthetableheading“SynthesisandRecommendations”.Thesystemshalldisplaythedetailedremarksasperthetablebelow.

R7:ShowStudentAttendance.

Prerequisite:Thestudenthastobeloadedintocontextfirst.

Thesystemshalldisplaytheattendanceforagivenstudentandforagivensemesterinasinglepageview.Thepageshalldisplaythetotalnumberofworkingdaysinasemester,thenumberofdaysthestudentwaspresentandthenumberofdaysthestudentwasabsent.Thisshouldbedisplayedinnumericalvalues,percentagesandwithabargraphasperthefigurebelow.

R8:StudentFees.

Prerequisite:Thestudenthastobeloadedintocontextfirst.

Foragivenstudentthesystemshalldisplaythemonthlyfeesstatus.Thisfeestobedisplayedincludesthetuitionfeesandthebusfees.Thisshallbeshownmonthlyforeachquarteroftheyear.Thefeesstatusfortuitionandbusshallbedisplayedasperthetablesbelow.

TheAdministrationModule

R9:ManageStudentAttendance.

Prerequisite:Thestudenthastobeloadedintocontextfirst.

Foragivenstudent,thesystemshalldisplaytheattendanceofboththesemestersinasinglepage.Underaseparateheadingforeachsemester,thesystemshalldisplaytotalworkingdays,totalnumberofdayspresentandtotalnumberofdaysabsent.

Thepresentfieldshallbeeditableandshallbedisplayingthepresentvalue.Theusershallbeabletoenteranumericalvalueandupdateittothesystem.Thisappliestoboththesemesters.Thepageshallholdclientsidevalidationsandmustposeappropriateerrormessagesforwrongvaluesentered.

Uponsuccessfulupdate,thesystemshalldisplaytheupdatedvalues.

Example:

Beforeupdate:Totalworkingdays:150

Present:140

Absent:10

Afterupdate:

Totalworkingdays:150

Present:145

Absent:5

Foragivenstudent,theupdateattendancefunctionalityshallbeasperthefiguresbelowforrespectivesemester.

R10:AddStudent.

Prerequisite:Theloggedinusermusthavetheroleprivilegestoaddastudent.

ThesystemshallprovidethisfunctionalityonlyfortherolesasperroleaccessmappingsinrequirementsreferenceR2.Thesystemshallprovideaformwiththefollowingfieldstoaddanewstudenttothesystem.Thesystemshallperformalltherequiredvalidationsatclientsideforthevaluesenteredforeachformelement.

Thesystemshallmandatefewformfieldsasshowninthetablebelowandotherfieldsshallbeallowedtobeoptionalbutrecommended.Thesystemshallautogenerateauniquestudentidbasedonthestudentname,studentbirthdateandparentsnamecombination.Andthisstudentidshallbeuniqueidentifierforallthestudentsbelongingtothesystem.

Theformshallhavethefieldsasperthetablesbelow.

Themandatoryfieldsaremarkedwiththe“*”symbol.Followingarethemandatoryfields:

Studentfirstname

Studentlastname

Mother’sfirstname

Father’sfirstname

Student’sdataofbirthinmm/dd/yyyyformat.Allotherfieldsshallbeoptionalbutencouragedtobefilled.

TheReportingModule

R11:ReportbyClass.

Prerequisite:Theloggedinusermusthavetheroleprivilegesforreportsbyclassfunctionality.

ThesystemshallprovidethisfunctionalityonlyfortherolesasperroleaccessmappingsinrequirementsreferenceR2.Forthisfunctionality,thesystemshallprovideapagewithtworegions.Oneforthereportcriteriaandotherforthereportresults.

Thereportcriteriashallcompriseofadropdownmenuforclassandadropdownmenuforsection.Theusershouldbeabletoselectaspecificclassandasectionanduponclickinggeneratereportbutton,thesystemshallquerythedatabaseandprovidethereportaspertheformatgivenbelow.

ReportCriteria

ReportResults

Thereportshallbedisplayedintabularformatasshowninthefigure.Itshalldisplaytheselectedreportcriteriaasaheadingfollowedbythereportresults.Thereportmustcontainfirstname,middlenameandlastnameinfirstcolumnfollowedbystudent

id,genderandbusidintheordermentioned.Bydefaultthereportresultsmustbesortedbyfirstnameofthestudentinalphabeticalorder.

TheHelpandMiscellaneousModule

R12:HelpPages.

Prerequisite:NoneSecurity:Publicpages

Thesepagesshallbepublicandtheaccessshallbegrantedtoeveryonei.e.fortheloggedinusersaswellasfortheuserswhodonothaveanid.Thatis,thesestaticpagesprovidinggeneralinformationshallbepublicinnaturewithoutanysecurityconstraints.Thesystemshallprovidethefollowingstatichtmlpagesunderaseparatemenuheadingtitled“Help”.Thehelppagesshallincluderesultslegendpage,FAQspage,holidayscalendarpage,escalationmatrixpageandfeestructurepage.

R13:HeaderandFooter.

Prerequisite:Theusermustbeloggedin.

Uponsuccessfullogin,thesystemshalldisplaytheconsistentheaderandfooteronallthepages.Theheadershalldisplaytheschoolnameonthetopinbiggerfonts.Theheadershallalsodisplaythedateandtime,theloggedinusername,thelogoutlinkandthetopnavigationalmenusaspertheloggedinuserrole(s).

Thefootershalldisplay,thecopyrightandotherstaticinformationinthegivenformat.

R14:TheMenu.

Prerequisite:Theusermustbeloggedin.

Uponsuccessfullogin,thesystemshalldisplaytheconsistentmenuforallthepagesofthewebapplication.Thefollowingmenusmustbedisplayedwiththerespectivemenuitemsasperthetablebelow.

5PROTOTYPING

TheprototypemodelstheUIofthewebapplicationtobebuild.Theobjectiveoftheprototypeistoensureandverifywhatexactlytheclientislookingfor.TheprototypepresentstheactualUI.WiththeseUIpages,thevendorshouldbeabletoexplaintheclientwhattheUIlookslikeindetailsandthevendorshouldalsobeabletoexplaintheclientthebehavioroftheapplicationbeingbuilt.

Thisisasetofhtmlpageswhichexactlydemonstrateshowtheapplicationlookslike.Typically,thegraphicsteamunderstandstheUIandUXrequirementsfromtheclientandotherstakeholders.Sometimes,theclientsharestheUIandUXrequirementsintheformofexcelsheetsormaybeevenimagefiles.Thegraphicsteamcomesupwiththelayout,headers,footers,colortheme,pagecontentareafortheapplicationtobebuilt.Thisteamprovidesavisualizationofthelooksoftheactualapplicationpages.

Theprototypeshowcaseshowtheapplicationslooksandbehaves.Itisasnearaspossiblemockupoftheapplicationinterfaceandbehavior.

Inourcase,wewillbuildthemockuporprototypeasHTMLpages.

Thepurposeofprototypeistoenablevariousstakeholdersinthedevelopmentofwebapplicationprojecttounderstandthesystembeingbuiltwithutmostclarity.Theprototypeactsassupplementarypractical,graphicversionofrequirementsspecification.ThedeveloperswhobuildtheUIgenerallydon’treadtherequirementsspecificationswordbywordrathertheybuildwhattheyseeintheprototype.Incaseofanyambiguityordoubttherequirementsspecificationsmustprovidemicrolevelclaritytothedevelopers.

Pagelayoutandtemplate

Thepagelayoutinourcaseissimple,wehaveaheaderandafooter.Theareainbetweentheheaderandfooterisusedforthesubjectivepagecontent.Thisisthedynamicregionwhichholdsthecurrentlyselectedpagebytheuser.

TheHeader

Theheaderdisplaystheschoolnameinabannermode.Theheaderhasthedropdownmenuwhichprovidestheuniversalnavigationfortheentireapplication.Theheaderdisplayscurrentdateandtime,theloggedinuserandthelogoutlink.

TheFooter

Thefootergenerallydisplaysthecopyrightinformationanddisclaimers.Inourcaseitshalldisplaythecopyrightinformationandthebooktitle.

TheDynamicContentRegion

Theheaderandfooterarestaticandarealwaysdisplayedforallthepagesintheapplication.Thedynamicregionasshowninthefiguredisplaysthepagetheuseriscurrentlyworkingon.Hence,inwebapplicationswegenerallyhaveaparentpagecalledthehomepagetemplatewhichhasallthestaticcontentsliketheheaderandfooter.Insomecaseswehavesidenavigationbutinourcasewedon’thavesidenavigationrathernavigationisprovidedviatopsidemenus.Basedontheuserinteraction,thedynamicregionisloadedwithrelevantpages.Thissavesthereloadingofthesamedataandhenceincreasestheapplicationperformance.Italsosavesnetworkbandwidthbyreducingthe

amountofdatatobeloaded.Thedevelopersfocusonthefunctionalitiesoftheindividualpagesandreusethepagetemplatewhichisdevelopedasasharedcomponent.

Letsnowbuildtheprototypeforallthepagesofoursampleapplication.Belowisthelistofusecasesandtheirrespectivepages.

Authenticateuser:Theloginpage.

Authorizeuserandrenderdashboardbasedonrole:Thedashboardpage.

Loadstudent:Theloadstudentajaxregionwithinthedashboard/homepage.

Getstudentdetails:Thestudentdetailspage.

Getstudentresults:Thestudentresultspage.

Getstudentattendance:Thestudentattendancepagesforsemester1andsemester2.

Getstudentfeesstatus:thestudentfeesstatuspage.

Managestudentattendance:Themanageattendancepage.

Addstudent:Theaddstudentpage.

Getreportbyclass:Thereportbyclasspage.Thishasbothreportcriteriaaswellasresult/reportdisplay.

Helppages:Theresultslegendpage.Thehelppagesareasetofstatichtmlpages.

Prototype1:LoginPage.SpecificationReference:R1

TheBisLogin.jsppageisbuiltusingthishtmlpage.Thesourcecodeforthispageisavailableinchapter15undertheauthenticationusecasesection.

Prototype2:Dashboard/HomePage.SpecificationReference:R2

TheBisDashboard.jsppageisbuiltusingthishtmlpage.Thesourcecodeforthispageisavailableinchapter15undertheauthorizationusecasesection.

Prototype3:LoadStudent.SpecificationReference:R3

ThisregioniswithintheBisDashboard.htmlpage.

Prototype4:StudentDetailsPage.

SpecificationReference:R4

TheStudentDetails.jsppageisbuiltusingthishtmlpage.Thesourcecodeforthispageisavailableinchapter15underthegetstudentdetailsusecasesection.

Prototype5:StudentResultsPageforSemester1.

SpecificationReference:R6

TheStudentAcademics.jsppageisbuiltusingthishtmlpage.Thesourcecodeforthispageisavailableinchapter15underthegetstudentresultsusecasesection.

Prototype5:StudentResultsPageforSemester2.

SpecificationReference:R6

TheStudentAcademics.jsppageisbuiltusingthishtmlpage.Thesourcecodeforthispageisavailableinchapter15underthegetstudentresultsusecasesection.

Prototype6:StudentAttendancePageforSemester1.

SpecificationReference:R6

TheStudentAttendance.jsppageisbuiltusingthishtmlpage.Thesourcecodeforthis

pageisavailableinchapter15underthegetstudentattendanceusecasesection.

Prototype6:StudentAttendancePageforSemester2.

SpecificationReference:R6

TheStudentAttendance.jsppageisbuiltusingthishtmlpage.Thesourcecodeforthispageisavailableinchapter15underthegetstudentattendanceusecasesection.

Prototype7:FeesStatusPage.

SpecificationReference:R8

TheStudentFees.jsppageisbuiltusingthishtmlpage.Thesourcecodeforthispageisavailableinchapter15underthegetstudentfeesusecasesection.

Prototype8:ManageAttendancePage.

SpecificationReference:R8

TheManageAttendance.jsppageisbuiltusingthishtmlpage.Thesourcecodeforthispageisavailableinchapter15underthemanagestudentattendanceusecasesection.

Prototype9:AddStudentPage.

SpecificationReference:R9

TheAddStudent.jsppageisbuiltusingthishtmlpage.Thesourcecodeforthispageisavailableinchapter15undertheaddstudentusecasesection.

Prototype10:Reportbyclasspagewithreportcriteriaoptions.

SpecificationReference:R10

TheReportByClass.jsppageisbuiltusingthishtmlpage.Thesourcecodeforthispageisavailableinchapter15underthereportbyclassusecasesection.

Prototype10:Reportbyclasspagewithreportdata.

SpecificationReference:R10

TheReportByClass.jsppageisbuiltusingthishtmlpage.Thesourcecodeforthispageisavailableinchapter15underthereportbyclassusecasesection.

Prototype11:Helppages,resultslegendpage.

SpecificationReference:R11

Type:Statichtmlpage.

ThesourcecodeforResultsLegend.htmlpageisavailableinchapter15underthehelppageusecasesection.

6THECLIENTSIDE

Thefaceofawebapplicationisabrowser.Thebrowserisasmartclientandithascomputationalcapabilities.Thebrowserisnotjustfordisplayingthecontentitalsoprovidescomputationalfunctionalitiesandplatformforotherweb2.0features.ThemostcommonlyusedtechnologiesusedinalmostallthebrowserbasedapplicationsareJavaScriptandCascadedStyleSheets.Inoursampleapplicationweareusingone.js(javascript)fileandone.css(cascadedstylesheet)file.Inthischapterwewillgothroughthesetwofilesindetail.

JavaScript

Thisisthemostpopularscriptinglanguageusedontheclientside.ThereareevenmanyframeworksbuiltwithJavaScriptandtheyareprettypopulartoo.JavaScriptisaobjectbasedprogramminglanguageandisusedforvariouscomputationsatclientside.Themostcommonusageisformvalidationandexecutingotherclientsidelogic.

Thejavascriptcodecandirectlybeembeddedinajsporahtmlpage.Butthepreferredwayistohaveseparate.jsfileandincludethatfileinthejsporhtmlpagewhereverrequired.Inoursampleapplication,weareusingBisScript.jsfileandthisisincludedinthehomepagetemplate.Thehomepagetemplateinturnincludesalltheotherjsppages.Thereby,wedon’thavetoincludethisfileinallindividualjsppages.Itisavailabletousinallthepagesaswehaveincludedthisinthehomepagetemplate.

BisScript.jsfunctionsubmitAddStdForm(){

document.getElementById(“paramAddStdFrmSubmitted”).value=“Yes”;document.getElementById(“frmAddStudent”).submit();

}

functiongenerateRptByCls(){document.getElementById(“frmReportByCls”).submit();

}

functionupdateAttendance(sem){

if(sem==‘1’){document.getElementById(“ParameterUpdateSemAttendance”).value=“1”;

}

elseif(sem==‘2’){document.getElementById(“ParameterUpdateSemAttendance”).value=“2”;

}

document.getElementById(“paramUpdateAttFrmSubmitted”).value=“Yes”;document.getElementById(“frmManageAttendance”).submit();

}

varxmlHttpReq=false;

functiongetStudentAJAX(){

varstdId=document.getElementById(“txtStdId”).value;

varurl=“BisAjaxControllerServlet?ParameterActionCommand=LoadStudent&txtStdId=”;

url=url+stdId;

xmlHttpReq=newXMLHttpRequest();

xmlHttpReq.open(“GET”,url,true);

xmlHttpReq.send();

xmlHttpReq.onreadystatechange=getStudentAjaxCallBack;

}

functiongetStudentAjaxCallBack(){

if(xmlHttpReq.readyState==4&&xmlHttpReq.status==200){document.getElementById(“dvStdSmry”).innerHTML=xmlHttpReq.responseText;}

}

ThejavascriptfunctionsubmitAddStdFormperformsthefollowingtasks:

SetsthevalueYestoparamAddStdFrmSubmittedflagandsubmitstheform.Ontheserversidethisflagisusedtoidentifywhethertheuserhassubmittedthefilledformorisrequestingtheaddstudentformpagetobefilledandsubmitted.

ThejavascriptfunctiongenerateRptByClsperformsthefollowingtasks:

Submitstheform.

ThejavascriptfunctionupdateAttendanceperformsthefollowingtasks:

Setsthesemesterincontext.

MarkstheupdateflagtoYes.

Submitstheform.

ThejavascriptvariablexmlHttpReqisusedbythetwoAjaxjavascriptfunctions.

TheloadstudentusecasedetailstheothertwoAjaxfunctionsgetStudentAJAXandgetStudentAjaxCallBack.

CascadedStyleSheet

Thecssisthemostcommonwayofpresentingthecontenttothebrowser.IncsswedefinethestylesforelementsandthesecanbereferencedfromthehtmlorJspdocuments.Eachhtmlstylecanbedefinedinlineoratadocumentlevelorinaseparate.cssfile.Thisfilecanbeincludedinthejsporhtmlpageandthestyledefinitionsinitcanbetiedtothehtmlelementsinthepage.Inoursampleapplication,weareusingonlyonecssfile.Thestylesforallthepagesinourapplicationaredefinedinthisfile.Also,thestyleforthemenusandmenuitemsarealldefinedinthisfile.Letshaveacloserlookatthisfile.

BISStyle.css

body{

background-color:#BBBBBB;

}

#dashboardlink{

color:Blue;

font-size:large;}

#trbgred{

color:white;

background-color:red;

}

#bigwhtxt{

color:White;

font-size:x-large;

}

#regfont{

color:white;

}

#headingfont{

color:Red;

size:7;

style:bold;

}

#headingtxt{

color:Red;

font-size:large;

}

#redFontWhiteBg{

color:red;

background-color:White;

}

#whiteBg{

background-color:White;

font-size:large;

}

#submitButton{

color:red;

background-color:White;

font-size:large;

}

#clred{

color:red;

}

#cssmenu{

width:auto;

border:1pxsolid#ff0000;

background:#ff0000;

}

#cssmenu>ul{

padding:1px0;

margin:0px;

list-style:none;

width:100%;

height:27px;

border-top:1pxsolid#FFFFFF;

border-bottom:1pxsolid#FFFFFF;

font:normal12ptverdana,arial,helvetica;

}

#cssmenu>ulli{

margin:0;

padding:0;

display:block;

float:left;

position:relative;

width:148px;

}

#cssmenu>ullia:link,#cssmenu>ullia:visited{

padding:4px0;

display:block;

text-align:center;

text-decoration:none;

background:#ff0000;

color:#ffffff;

width:148px;

}#cssmenu>ulli:hovera,#cssmenu>ullia:hover,#cssmenu>ullia:active{

padding:4px0;

display:block;

text-align:center;

text-decoration:none;

background:#ff4d4d;

color:#ffffff;

width:146px;

border-left:1pxsolid#ffffff;

border-right:1pxsolid#ffffff;

}

#cssmenu>ulliul{

margin:0;

padding:1px1px0;

list-style:none;

display:none;

background:#ffffff;

width:146px;

position:absolute;

top:21px;

left:-1px;

border:1pxsolid#ff0000;

border-top:none;

}

#cssmenu>ulli:hoverul{

display:block;

}

#cssmenu>ulliulli{

clear:left;

width:146px;

}

#cssmenu>ulliullia:link,#cssmenu>ulliullia:visited{

clear:left;

background:#ff0000;

padding:4px0;

width:146px;

border:none;

border-bottom:1pxsolid#ffffff;

position:relative;

z-index:1000;

}#cssmenu>ulliulli:hovera,#cssmenu>ulliullia:active,#cssmenu>ulliullia:hover{

clear:left;

background:#ff4d4d;

padding:4px0;

width:146px;

border:none;

border-bottom:1pxsolid#ffffff;

position:relative;

z-index:1000;

}

#cssmenu>ulliulliul.navigation-3{

display:none;

margin:0;

padding:0;

list-style:none;

position:absolute;

left:145px;

top:-2px;

padding:1px1px01px;

border:1pxsolid#ff0000;

border-left:1pxsolid#ff0000;

background:#ffffff;

z-index:900;

}

#cssmenu>ulliulli:hoverul.navigation-3{

display:block;

}

#cssmenu>ulliulliul.navigation-3lia:link,#cssmenu>ulliulliul.navigation-3lia:visited{

background:#ff0000;}

TheBISStyle.cssandBISScript.jsfilesareincludedintheBisHome.jsppage.Thispageinturnincludesallotherjsppagesbasedontheusecase.Inordertousethesefiles,thefollowingcodeisaddedinBisHome.jsppage.Accordingly,theBISStyle.cssfilesisplacedunderresources/cssfolderandtheBISScript.jsfileisplacedunderresources/jsfolder.

<head>

<linkrel=“stylesheet”type=“text/css”href=“resources/css/BISStyle.css”></link>

<scriptsrc=“resources/js/BISScript.js”></script>

</head>

Menus

Fortheimplementationofthemenus,pleaserefertheBISStyle.csssourcecodeinthischapterandBisHome.jspsourcecodeinchapter14.

7THEPATTERNS

Apatternisaprovenwayofapproachingthesolutionforaknowtypeofproblem.Agivenproblemcanbesolvedinmanyways.Theapproachwhichprovidesthebestsolutionandwhichisalreadytriedandtestedbyothersconstituteapattern.Patternsprovidereadymadesolutionsforaknowntypeofproblem.Patternsbasicallyreusehumaneffortsandintelligencewhichisalreadyinvestedbyothers.

Letusunderstandpatternwithanexamplefromourdaytodaylife.Aschoolbusdriverpicksanddrops20studentsfromvariouslocationsinacity.Thedriverhasapatternforthepickupbasedonthenoentries,trafficconditions,weatheretcduringmorninghours.Thedriveralsohasapatternfordroppingthestudentsbasedonthesaidconditionsintheevening.Thedriverwillpickanddropstudentsinaparticularorder.Thisorderevolvesafterfewweeksfromthebeginningoftheacademicyear.Thedrivermaypickthestudentnearesttotheschoolinthelastandthedrivermaydropthesamestudentfirstintheevening.Thedriverofthisschoolbusthuseventuallyhasthebestwayafterfewweekstosavetime,fuelandeffortsforthistask.Thedriverstickstothispatterntoachievethesaidgoals.

Now,letstakeascenariowherethedriverquitsthejob.Inthiscase,thenewdriverwillnotreinventthewheel.Thenewdriverwilllearnthepathandtheorderetcfromtheolddriverwhoisquitting.Wecannowsaythat,theolddriverhasputintelligence,efforts,time,moneyetctocomeupwiththebestpatternforpickingupanddroppingthestudents.Thenewdriverhastojustreusethishumaneffortandintelligencewhichistried,testedandproven.Thisisnothingbutestablishingapatternandreusingit.

ArchitecturalPatterns

Thesearepatternsatarchitecturallevel.Thesepatternsfocusatabiggerpictureatthesystemlevelstructureofmodules,componentsandevenapplicationswithinandoutsideanenterprise.ServiceOrientedArchitecture(SOA),ModelViewController(MVC)anddependencyinjectionarethemostcommonlyusedarchitecturalpatterns.

MVC

Pleasereferchapter10fordetailedexplanationandimplementationofaMVC

basedarchitecturalpattern.

DesignPatterns

Thesearethepatternsatdesignlevel.Thedesignpatternsprovidesolutionstothecommonlyencountereddesignproblems.ThemostcommonlyuseddesignpatternsareSingleton,Factory,Command,Iterator,BridgeandAdapteretc.

Letshaveacloserlookatthepatternsusedinoursampleapplication.

CommandPattern

Thisisbasicallyadesignpatternandisfurthercategorizedunderbehavioralpatterns.Incommandpattern,theclientsendsacommandandbasedonthecommandtheserverexecutesafunctionalityandreturnstheresulttotheclient.

InoursampleapplicationandMVCbasedframeworkweexploitcommandpattern.Letsseethiswithanexampleofausecase.Ifyoulookatthegetstudentdetailsusecase,Theuserclickgetstudentdetails,thissendsthe“getStudentDetails”commandtotheserver.Theserverinvokesthecontrollerservlet,withinthecontrollerservletweuseacommandprocessorclassforeachcommand.Inthiscase,thecontrollerservletinstantiatesGetStudentDetailsCPclassandinvokestheexecutemethod.Thisclassholdsthebusinesslogicforgetstudentdetailscommand.Thisclassleveragesotherserviceclassesandutilityclassestogetthestudentdetailsfromthedatabase.Andfinallyreturnstheviewwiththestudentdetails.

Hence,incommandpatternweseethattheclientsendsarequestoracommandtotheserver.Theserverdelegatesthiscommandtotheframeworkwhichinturninvokesthespecificcommandhandler.Thecommandhandlerexecutesthebusinesslogicpertainingtothecommandandnavigatestheusertoanappropriateview.FormoredetailsoncommandpatternpleasegothroughtheBisMVCframeworkflowdescriptioninchapter10andalsopleasegothroughtheindividualusecasesimplementationtogetfurtherunderstandingandclarity.

FrontControllerDesignPatten

Inthisdesignpattern,wehaveacentralizedentrypointforparticulartypeofclientrequests.Thispatterniscommonlyusedinframeworkswhichareusedforbuildingweb

applications.

Inourframework,weuseBisControllerServletasanentrypointforalltheclientrequests.WehaveanothercontrollerservletwhichistheentrypointforallAjaxrequestsfromtheclient.TheBisAjaxControlerServlethandlesonlyajaxrequestsinourframeworkanditactsasfrontcontrollerforalltheAjaxcallsfromtheclient.

Thispatternhelpsalotindebugging.Bysettingabreakpointatthecontrollerservletwecantracealltheexecutionflows.

ValueObjectDesignPattern

Inthispatternweusesimplejavabeanswithprivatefieldsandpublicgettersandsettersmethodsforthosefields.Inoursampleapplicationweusethispatternheavily.Forexampleinthegetstudentdetailsusecase,weaddallthedatarelatedtostudenttoaStudentDetailsBean.Thisdataisfetchedfromoneormoretablesfromthedatabase.Thisgivesusahandyobjecttoprocessthestudentrelateddataatthejavatier.Weaddthisobjecttothesessionandconsumeitfortheviewpurposeatthejsppagelevel.Thispatternhelpsincreatingaviewbasedontheusecaserequirements.Thisalsohelpsinputtingrelevantorrelateddatainasingleobjectwhichisveryhandyforthedevelopers.

Thereareotherdesignpatternswhichareusedinoursampleapplications.Therearemanyotherdesignpatternswhichcanbeusedinoursampleapplication.Basedontherequirements,architecture,performancecriteria,userbase,supportrequirements,typeofapplicationandmanyotherfactorsthedesignpatternshavetobechosenandimplemented.

8THEARCHITECTURE

Architectureistheblueprintoftheapplication.Thisgivesthearielviewofthesystemtobebuilt.Thearchitectureprovidesthebiggerpictureinasingleviewcomprisingofallthesignificantbuildingblocksofthesystem.

Thearchitectureisaverybroadandoldtermusedinalmostallbranchesofengineering.Letstakeanexampleofacivilengineeringprojecttounderstandwhatanarchitectureis.Letstaketheexampleof“BaigApartments”,thisapartmentneedstohave7floorsandeachfloormusthave3flats.Theplotsizetobuildthisapartmentis10,000squarefeet.Therequirementisverybasicandquantifiedataveryhighlevelinthiscase.Thearchitectureneedstobebuiltfirst,thancomesthestructuraldesignandthentheactualbuildingwillbebuiltbasedonthedesign.

Thearchitectureinthiscaseprovidesthearielvieworthebiggerpictureoftheapartmenttobebuilt.Thearchitecturedetailstheplacementofeachflatonafloorwiththedimensionsofeachroom,hall,kitchenetc.Thearchitecturedetailsthespaceforutilities,parkingandothersignificantentitiesofabuildingofthissizelikethelift,staircaseetc.Thecolorofthewalls,thematerialusedforflooring,theinteriorofthekitchenetcareoutsidethescopeofthearchitecturaldetails.Agoodarchitectureisessentialtobuildasystem.Itprovidesustheflexibilitytovisualize,model,designandmodifyasystembeforeitisbuilt.

TheBIS-SMSApplicationArchitecture

Insoftwareengineering,thearchitecturedetailsallthebuildingblockoftheapplication.Italsodetailstheinteractionandthetypebetweenvariouscomponentsofasoftwaresystemtobebuilt.LetsnowdrawthearchitectureofBIS-SMSapplication.Thisarchitecturemustshowcaseusfrombrowsertobrowsertraceinabiggerpicture.Thatis,itmustshowuswhathappenswhenarequestissentfromabrowsertillwereceivebacktheresponsetothebrowser.Thismustbedepictedinadiagramatacomponentormodularlevel.

Thebrowsersendsahttprequesttotheserver.Theserveridentifiestherequestandinvokesthecontrollerservlet.Thecontrollerservletidentifiesthecommandandinvokestheappropriatecommandprocessor.Thecommandprocessorbasedontheusecaseleveragesoneofmoreserviceclasses.Theserviceclassesholdthebusinesslogicandmayinteractwiththedatabaseusingdatabaseserviceclass.Theserviceclassesprovidetheservicesforspecificusecases.Basedontherequesttype,theserviceclassescookupthebeansandpopulatethedatainoneormorebeanstoprovideitbackwiththeresponse.Incaseofinsertorupdateoperations,theserviceclasseswillprovideonlyaflagconveyingsuccessorfailure.Incaseofaviewrequest,theserviceclasses,querythedatabaseaddthesevaluestobeansandreturnthecontroltothecommandprocessorforrenderingaspecificview.

Notethatintheabovearchitecturaldiagramanddescriptionwehavelookedatthethingsinabiggerpictureandnotdwelledintothemicrodetailsofanyspecificinteractionorcomponent.

Webuildthisarchitectureafterhavingaclaritywithrequirementsandaftertechnologyselection.Thenextthingistolistanddetailalltheusecasesandthencreatedetaileddesignforeachusecase.ThedetaileddesignmustbeprovidedwithvariousUMLdiagrams.Theobjectiveofthearchitectureisservedifithelpsincomingupwithdetaileddesign.Oncethedetaileddesignisready,thesystemcanbeimplemented(Generallyviacoding).Itisimportantthattheimplementedsystemmustbeincompliancewiththearchitecture.

9DATABASEDESIGN

Oncewehavecompleteclaritywiththerequirementsi.e.oncewehavethefrozenandsignedrequirementsspecifications,wecomeupwiththedatabasedesign.

ForBISSMSwebapplication,weneedfollowingtwoschemas:

BisSecurityRealmSchema

Thisschemaisexclusivelyusedforusers,rolesandpermissions.Inthisschemawehavetwotablesoneforusersandotherfortheroles.TheER-diagrambelowdetailsthesetables.

UsersTable

Theuserstablehastwocolumns.Theusernamecolumnstorestheusernameandisaprimarykeyforthistable.Theuserpasswordcolumnstoresthepassword.

UserRolesTable

Theuserrolestablealsohastwocolumns.Theusernamecolumnstorestheusernameandisaforeignkeytotheusernamecolumninuserstable.Therolenamecolumnstorestherole.

BisSchema

Thisistheapplicationschemaandisusedforapplicationspecificdata.TheER-diagrambelowdetailsthetables.Forthesampleapplicationweareonlyusingdatabasetablesandnototherdatabaseentitieslikeview,triggersetc.Thedatabaseisdesignedforaparticularacademicyearandhence,thedatahastobepurgedattheendofeachacademicyear.However,thisdesigncanbeenhancedformultipleacademicyears.

Letstakeacloserlookateachofthesetablesandtheirrelationships.

StudentDetailsTable

Thestudentdetailstableholdsonerecordforeachstudentandisuniquelyidentifiedbystudentid.Thisisthecoretableforalltheinformationrelatedtostudents.

ParentDetailsTable

Thistableholdsthedetailsofthestudent’sparent’s/guardian’s.Thestudentidhereisaforeignkeytothestudentdetailstable.

EmployeeDetailsTable

Thistableprovidesusalltherelevantinformationabouttheemployeesoftheschool.Theemployeesinclude,theteachingstaffandthenonteachingstaff.Forexample,thistableprovidesustheinformationoftheclassteacheraswellasthebusdriver.

TransportationDetailsTable

Thestudent’scommuteinformationisfetchedfromthistable.

ClassTeacherMappingTable

Thisisalookuptablewhichprovidesusidentifyingclassteacherforagivenclassand

section.

StudentAttendanceTable

Foragivensemesterandforagivenstudent,thistableprovidestheattendancedetails.Thistableisdesignedtoprovidetheattendanceonlyforthecurrentacademicyear.

StudentFeesTable

Foragivenstudent,thistableprovidesalltheinformationaboutTuitionaswellastransportationfees.

ScholasticResults/CoScholasticResultsTables

Thesetwotableholdallthedetailsaboutthestudent’sresults.Theseareexampletablesforlearningpurposeonlyandarenotdesignedforanyparticularboardorabody.Thesetableshavetobedesignedaccordinglyforaspecificboardorabody(basedonthecountryandeducationsystem).

BISConstantsTable

Thistableisusedonlyforstoriespropertieswithavalue.Fore.g.theschooltelephonenumbercanbestoredinthistable.Ifthetelephonenumberchanges,wehavetoupdateitinthistableforagivenproperty.

Theapplicationsconsumingthistablemustbedesignedaccordingly.Hence,wegetsmartapplicationswhereweneitherhavetomodifythecodenorhavetoredeploytheapplication.

10THEFRAMEWORK

Aframeworkprovidestheplatformtoquicklybuildapplicationsusingit.Theframeworkholdsallthecommonfunctionalities.Aframeworkisareusableentityandithelpsinquicklybuildingapplicationsbyfocusingonlyontheapplicationspecifics.Reusability,productivity,bestpractices,provenpatterns,finetunedperformance,scalability,compliancetostandards,plugandplayarethemainadvantagesofusingframeworks.

Therearemanyopensourceandpaidframeworksavailableinthemarketwhicharebasedonmanyprovenarchitecturalanddesignpatterns.

TheMVCBasedJavaFrameworkInthischapterwewillbuildourownlightweightMVCbasedJavaFrameworkforweb

applications.Thiswillgiveusacompleteinsightandknowhowofaframework.Thisframeworkwillthanbeusedforbuildingourapplicationsontopofit.WewillfollowtheindustryrecognizedandprovenMVCpattern.Inthisarchitecturalpattern,therearethreeentities:themodel,theviewandthecontroller.Eachentityhasitsownspecificfunctionality.

ViewLayerThisistheuserinterface(UI)layerwhichtheenduserseesandinteractswithit.Ona

desktopbrowserviewisrenderedashtmldocumentwhichhascontentandthepresentation.Inourframework,thehtmlandjsppagesconstitutetheview.

ModelLayer

Modelrepresentsthestateofdataduringruntimeontheserverside.InJava,weusebeansformodel.Thesebeansholdthedatainaparticularstate.

ControllerLayer

Asthenamesuggests,thecontrollerlayertakeschargeofthecontrolandflow.Thecontrollerdecideswhatfunctionalityneedstobeinvokedonaparticularinteractionfromtheuser.Thecontrolleralsodecidesnavigationflowandtheviewtoberenderedtotheuser.Typically,aServletisusedasacontroller.

Allthehttprequestsfromtheclientandallthehttpresponsestotheclient(typically,awebbrowser)goesviathecontroller.Basedontheclientrequest,thecontrollerinvokesparticularservice.Theserviceinturnpreparesmodelandfinallytheviewisrenderedbacktotheclient.

BisFramework

WewillnowbuildourownlightweightMVCbasedJavaframework.LetscallitBisFramework.

TheBisFrameworkArchitecture

Intheabovefigure,wehave3tiers.Theclienttier,thewebservertierandthedatabasetier.

ClientTier

Theclienttiertypicallyconsistsofawebbrowser.ThefigureshowsGooglechromeastheclient.

DatabaseTier

Thedatabasetierconsistsofadatabase.InourcaseweareusingOracleXEwithtwoschemasoneforauthenticationandauthorizationandotherfortheapplication.

WebServerTier

ThewebservertieriscomprisedofApacheTomcat.ThisprovidesusthecapabilityofawebserverandaServletcontainer.ThewebserverdealswiththehttpprotocolrequestsandresponsesandtheServletcontainerprovidestheruntimeenvironmentfortheServletsandJSP(JSPSarecompiledtoServletsatruntime).

ViewLayer

TheviewlayertakescareofmanagingtheUI.Itcapturestheuserinteractionsanddisplaystheoutput.TheconstituentsofviewareJspandhtmlpages.TheJavaScript.jsandthecascadedstylesheet.cssfilesbelongtotheview.BisHome.jspisanexampleviewshowninthefigure.

ControllerLayer

ThecontrollertypicallyconsistsofoneormoreServlets(generallyoncontrollerServlet)InourcasethecontrollerServletisBisControllerServlet.AlltherequestsandresponsestotheclientflowthroughthisServlet.Thiscontrollerprimarilytakeschargeofinvocationofservicesbasedonrequestandnavigationflow.

ModelLayer

Themodelcomprisesoftheserviceclassesandthebeansclasses.Thebeansrepresentthestateofdatainduringtheruntime.Theserviceclassesimplementthebusinesslogic.TheAPIthatinteractswiththedatabaseareleveragedfromtheModellayer.

CommandProcessor

ThecommandprocessortakeschargeformthecontrollerServlet.Foragivenrequestcommand,thesubjectivecommandprocessorisdynamicallyexecutedbythecontrollerServlet.EachcommandobjectthanorchestratestheexecutionontheModelforthespecificusecase.Toputitsimple,thecontrollerreadstheclientrequestandhandoversthetasktoaparticularcommandobject.Thecommandobjectinturninvokesthemodeltoachievethespecifictask.

Toachievethis,thecontrollerjustcallstheexecutemethodofthecommand.

BisCommandisaninterfacewhichholdsonlyonemethodcalledexecute.AllthecommandprocessorsimplementtheinterfaceBisCommandtoqualifyascommandprocessor.Thecommandprocessorclassesaresuffixedwith“CP”,e.g.AddStudentCP.EachCPissubjectiveforitsaction.TheCPscallthesubjectiveservicesforagiventask.Uponexecutionofthecompleteflow,eitherabeanispopulatedorachangeismadeinthedatabase.Ifitisaview,thebeanispopulatedandaddedtosession.Theviewthanconsumesthebeananddisplaystheoutput.

TheControlFlow

Inordertounderstandthecontrolflow,letstracetheflowfromthebrowserrequesttillresponse.Inthefigureaboveletshaveacloserlookateachflownumberedfrom1to15.

1.Inthisflow,thebrowsersendsahttprequesttotheserver.

2.TheserverinvokestherequestedServlet,inthiscasetheBisControllerServlet.

3.AllcommandprocessorsimplementtheBisCommandinterfaceinordertoqualifyasacommandprocessor.ThishelpsthecontrollerservlettoleverageJava’spolymorphicfeaturetodynamicallyexecuteaspecificcommandprocessor.Pleaserefertheservicemethodofthecontrollerservlet’scodetogetmoreclarityonthis.

4.Thecontrollerservletinstantiatesaspecificcommandprocessorbasedontherequestcommandpassedbytheview.Thiscommandistypicallypassedasahtmlhiddentypefromtheview.ThecommandisgenerallyaverbwhichconveystheuserinteractionwiththeUI.Thecontrollerservletinvokestheexecutemethodofthecommandprocessor.

5.Thecommandprocessorinstantiatesandinvokestherequiredserviceclasses.

6,7,8.Thecontrolflowtakesthisrouteiftheserviceclassneedsaninteractionwiththedatabase.DatabaseServiceisajavaclasswhichprovidesallthemethodstointeractwithaparticulardatabase.

9.Theserviceclasspopulatesoneormorejavabeansviasettersiftheuseisagetrequestfordata.

Incaseofinsertorupdateactiontothedatabase,thecontrolflowvaries.Thebeansarefirstpopulatedfromtherequestandthanthevaluesarepassedtothedatabase.

10,11,12,13Uponsuccessorfailure,theserviceclassreturnsbackthecontroltothecommandprocessor.Basedontheresult,thecommandprocessorassignsthenextviewnameandreturnsbackthecontroltoBisControllerServlet.

14.Thecontrollerservletusesthereturnedviewnameandbasedonthatredirectsthehttpresponsetoaparticularview(Jsppage).

15.Theserversendsbackthehttpresponseoftheview(Jsppage)tothebrowser.Theuserseesthenextpagewhichhe/shehadrequested.

11THELOGGING

Whatisloggingandwhyitisneeded?

Loggingisamechanismtorecordtheactivitiesperformedbyasoftwareprogramduringexecution.Whenasoftwareprogramisexecutedlinebylineitaccomplishescertainintendedtask.Duringtheexecution,theprogramlogsthesuccess,failures,importantactionoranyothersignificantinformationintoafile.Thisfileisknownasalogfileandisusedtomonitorthehealthaswellasthejobofthesoftware.Themostcommonusageofloggingistoidentifysystemandbusinesserrorsandithelpsinfixingthem.Logginghelpsinsmoothlyrunningthesoftwaresystembyprovidingtherequiredinformationtothesupportteam.Inabroadersense,logginghelpsalotinsoftwaresystemgovernance.

InoursampleapplicationweareusingLog4j.Apachelog4jisaloggingutilityanditprovidesreadymademechanismtoenablelogginginjavaapplicationswithlittleconfigurations.

LoggingLevels

Insomeapplicationsorusecasesweneedextensiveloggingwhereasinsomeotherapplicationsorusecaseswemayneedloggingonlyincaseofanerrororifsomethinggoesreallyfatal.Logginglevelsprovideusanoptiontoconfigurewhatlevelofloggingisneeded.Forexample,ifthesupportteamisanalysisabugtheymaysettheloggingathighestlevelaslogatALLlevelsprovidesmoreinformation.Withlog4jthefollowingloglevelsareavailable.

ALL-Logseverything.

DEBUG-Whiledebugginganissue.

ERROR-Logserrorsandexceptions.

FATAL-Logscriticalerrorsthatcouldpotentiallyterminatetheapplication.

INFO-Providesinformationabouttheprogressoftheapplicationfore.g.anewstudentissuccessfullyadded.

OFF-Forturningoffthelogging.

WARN-Forwarnings.Fore.g.asqlinjectionisattempted.

TRACE,TRACE_INTandaretheotherfinergrainedlevelsoflogging.

UsingLog4jinjdeveloper

InordertouseLog4jdownloadthelatestversionofLog4j.jarfileandaddittothelibrary.Inordertoaddajarfiletoaprojectlibraryinjdeveloper,pleasefollowthestepsbelow:

Step1:RightclicktheBISViewControllerprojectandselectprojectpropertiesasshowninthefigurebelow.

Step2:Theprojectpropertieswindowopensup.Inthiswindow,selectlibrariesandclasspathasshowninthefigure.

Step3:ClickaddJAR/DirectorybuttonandthenbrowseandselecttheLog4j.jarfile.ClickOKtoclosethewindow.

TheLog4j.jarfileisnowaddedtotheprojectlibrary.

Usingloggerinjavaclasses.

Inordertousetheloggerwithinthejavaclasses,declareastaticclassvariablefortheloggerasshownbelow.

publicclassLoadStudentCPextendsBisCPimplementsBisCommand{

staticLoggerlogger=Logger.getLogger(LoadStudentCP.class);

NotethatthespecificclassnamemustbepassedasanargumenttothegetLoggermethod.Intheabovecodesnippet,theclassnameispassedasLoadStudentCP.classasthisloggerisusedwithintheclassLoadStudentCP.

Theloggerhandlecannowbeusedwithinthescopeofthisjavaclasstoperformvariousloggings.Wecannowusevariousmethodsavailableintheloggerforlogging

errorsorinformationoranyotherdetailswewanttologatvariouspointsinourcode.

Forexamplewewillusethefollowingcodeinordertologtheexceptionmessageaterrorlevel.

catch(Exceptione){

logger.error(e.getMessage());

}

Similarly,tologsomethingasfatal,infoanddebugweusetherespectivemethods.Pleaserefertheapplicationjavacodetoseehowloggingisusedatvariouslevels.

Thelog4j.propertiesfile

Thelog4j.propertiesfileisusedtoperformvariousconfigurationsforthelogger.Thispropertiesfileismostcommonlymodifiedforchangingthelogginglevels.ThesamplewebapplicationisdeployedinApacheTomcatserverhencethelog4j.propertiesfilemustbeaddedtothe$CATALINA_BASE/webapps/Bis/WEB-INF/classesfolder.Theloggerconfigurationsweusedforsampleapplicationisasshownbelow.

log4j.debug=true

log4j.rootLogger=INFO,CATALINA

log4j.appender.CATALINA=org.apache.log4j.FileAppender

log4j.appender.CATALINA.file=${catalina.base}/logs/bis.log

log4j.appender.CATALINA.encoding=UTF-8

log4j.appender.CATALINA.layout=org.apache.log4j.PatternLayout

log4j.appender.CATALINA.layout.conversionPattern=%d[%t]%-5p%c-%m%n

log4j.appender.CATALINA.append=true

Theseconfigurationpropertieshaveselfexplanatorynames,forexamplelog4j.appender.CATALINA.fileisthenameofthelogfiletobecreatedorused.Thevalueforthisis${catalina.base}/logs/bis.logthismeansthatthelogfilenamedbis.logwithinthefolderlogswillbecreatedorused.

Belowarethesampleerrormessagesfromthebis.logfile.

2015-04-2310:51:07,384[http-nio-80-exec-4]ERRORcom.bis.cp.BisDashboardCP-Studentidisnull

2015-04-2310:51:10,034[http-nio-80-exec-7]ERRORcom.bis.session.reports.ReportByClassService-Section/Classisnull

2015-04-2310:51:18,038[http-nio-80-exec-2]ERRORcom.bis.cp.BisDashboardCP-Studentidisnull

2015-04-2310:51:28,966[http-nio-80-exec-6]ERRORcom.bis.session.StudentDetailsService-Invalidcolumnname

12SESSIONMANAGEMENT

UnderstandingSession

Aninteractionbetweenauserandtheapplicationwhereanobjectiveoftheuserisservediscalledthesession.Forthisinteractiontotakeplace,theuserstartswiththeloginactivityandthentheuserperformsoneofmoreotheractivitieswiththeapplicationtoachievehis/herobjectiveofthatparticularinteraction.Thentheuserlogsout.Thisinteractionbetweentheuserandthesystemwhereinwhichtheuserlogsin,performsoneormoreinteractionsandthenlogsoutiscalledsession.Theperiodbetweenauser’sloginandlogoutiscalledthesessionperiod.Duringthesessiontheloggedinuseraccessesthevariousfunctionalitiesofthewebapplication.

Forexample,weuseemailserviceslikeyahoomailandgmail.Inordertousetheseemailservicesweloginfirst,thenweperformoneormoreofthefollowingactivities:checkemail,readoneormoreemails,deleteoneormoreemails,sendoneormoreemailsetc.Onceourtasksisdonewelogoutoftheemailservice.Thisisknownasasessionbetweentheuserandtheemailservice.

OnceauserlogintoourBIS-SMSapplicationweneedtotrackthestateoftheuser’sinteraction.Thatis,weneedtorememberattributesoftheuser’sinteractionwiththesystem.Like,thestudentcurrentlyincontext.Therearevariouswaystorememberandusesuchvalues.

Theothersignificantrequirementforsessionmanagementistheidentificationofusers.Supposetendifferentusershaveloggedintothesystemwithdifferentuseridsandroles.Thereshouldbeamechanismtouniquelyidentifyeachuserattheserverside.Thisisachievedusingsessionids.Eachloggedinuserattheserversideisuniquelyidentifiedwithasessionid.

LeveragingHttpSessionInourapplicationweuseHttpSessionforsessionmanagement.HttpSessionisaninterfaceinjavax.servlet.httppackage.Thisinterfaceenablesustoidentifyauseracrossmorethanonepagerequesttoawebapplication.Thisinterfacealsoprovidesusanoptiontostoreinformationaboutthatuser.Fore.g.Theloggedinuserpadma.kulkarnimightbe

browsingthestudentZainBaigandtheotherloggedinuseshamim.banumightbebrowsingtheuserNeetalShah.AlltheseinformationarestoredinuserspecificHttpSessionobjectforeachloggedinuser.TheservletcontainerusesHttpSessioninterfacetocreateasessionbetweenahttpclientandahttpserver.

Belowisthecodesnippettoaddstudentidtothehttpsessionwithinthecommandprocessor.

HttpSessionsession=null;

strStudentId=request.getParameter(“txtStdId”);

session=request.getSession();

session.setAttribute(“StudentId”,strStudentId);

Thiscodeisfromtheloadstudentcommandprocessor.Herewegetthestudentidenteredbytheuserviarequest.getParameter(“txtStdId”).

Fortheloggedinuserthisstudentidremainsinthesession.Whenthisuserclicksgetstudentdetails.Thestudentidisfetchedfromthesession.Belowisthecodesnippetforthat.

HttpSessionsession=request.getSession();

strStudentId=(String)session.getAttribute(“StudentId”);

Thestudentidistiedtoahttpsessionandthishttpsessionbelongstoaparticularhttpclient.Whenthesameclient(browserortheuser)sendsarequestforstudentdetailspage.Thestudentidisreadfromthehttpsessionbelongingtothishttpclient.

Thesessionforauseriseitherinvalidatedautomaticallywithtimeoutorexplicitlyinvalidatedwhentheuserlogsout.

Therearemanywaystomanagesessioninawebapplication.Inoursampleapplicationwedidnotusecookiesforsessionmanagement.Primarily,wehaveusedHttpSessionfromtheservletAPIforthesessionmanagementinoursamplewebapplication.Besidesthis,wehavewealsousedhiddenvariablesforsomeusecasesimplementation.Pleaserefertheindividualusecasesintheimplementingusecaseschaptertogetmoreclarity.

13INTERACTINGWITHTHEDATABASE

Inoursampleapplicationwehave3tierarchitecture:theclienttier,thewebservertierandthedatabasetier.Theclientinteractswiththewebserverandformostoftheusecasestheserverinteractswiththedatabasetier.Inourdatabasetierwehavetwoschemasoneusedbytheserverforauthenticationandauthorizationandtheotherusedbytheapplication.

Weneedlotsofinteractionbetweenourapplicationandthedatabase.AllourapplicationtablesareintheBisschema.Inthischapterwewilltakeacloserlookatallthetypeofinteractionsthathappenbetweenourapplication/serverandthedatabaseserver.

TheapproachesfordatabaseconnectivityJavaDatabaseConnectivity(JDBC)isthetechnologyusedinJavaforinteractingwith

thedatabases.Wecangetadatabaseconnectionbydirectlyusingtheoracle’sdriversforJDBCconnectivity.TheotherwayistogetthedatabaseconnectionfromtheserverviaaJNDIlookupforthedatasource.Usingdatasourceisabetterapproachaswegetlotofoutoftheboxadvantageswithit.Alsousingdatasourcesistherightapproachinthedistributedcomputingparadigm.Hence,inourapplicationwehavetakenthisapproach.

UsingDataSources

Workingwithdatasourceshastwoparts.One,creatingadatasourcewithconnectionpoolontheserver.Two,lookingupthisdatasourcefromtheapplicationcode.

Inthepopularapplicationservers,wegetGUIforcreatingconnectionpoolanddatasources.IncaseofApacheTomcatserverweneedtoaddanentrytocontext.xmlfiletocreateadatasource.Chapter21detailshowtocreatedatasourceinApacheTomcat8.IncomponentschapterundertheDatabaseService.javasectionweseehowtolookupthedatasourceviaJNDIandwealsoseehowtogetconnectionandreleasedatabaseresources.Thevarioususecasesinthechapterimplementingusecasesdetailhowtoperformcreate,update,deleteandreadoperations.Thisisexplainedindetailwiththesourcecodeforeachtypeofoperation.

14THEBIS-SMSPROJECTCOMPONENTS

ThesampleprojectBaigInternationalSchool-StudentManagementSystemisbuiltusingthefollowingsoftwarecomponents:

JavaServletsCommandProcessorsServiceClassesJavaBeansUtilityClassesJavaServerPages(jsp)Log4j

JavaServlets

Ajavaprogramthatrunsontheserverside.AjavaclassgetsqualifiedasaservletbyimplementingtheServletinterface.Thelifecycleofaservletismanagedbytheservletcontainer.InBIS-SMSapplicationweusetwoservlets,theControllerServletandAjaxControllerServlet.

TheControllerServletisthecentralizedpointforalltheclienthttprequestsexceptfortheAjaxcalls.Thecontrollerservletreturnsaviewasajsp.TheAjaxControllerServletisadedicatedcentralizedpointforalltheclientAjaxcalls.Theajaxcontrollerservletreturnsaresponsetext.

BoththecontrollerservletandtheajaxcontrollerservletextendHttpServletandoverridetheservicemethod.TheHttpServletextendstheGenericServletwhichinturnimplementstheServletandServletConfiginterfaces.

ControllerServlet.java/*

*@AuthorMirzaYousufAhmedBaig

*@ControllerServlet.java

*@Copyright:BuildwebapplicationswithJava.

*/

packagecom.bis.servlet;

importcom.bis.cp.BisCommand;

importjava.io.IOException;

importjavax.servlet.RequestDispatcher;

importjavax.servlet.ServletConfig;

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importorg.apache.log4j.Logger;

publicclassControllerServletextendsHttpServlet{

privatestaticfinalStringCONTENT_TYPE=“text/html;charset=windows-1252”;

staticLoggerlogger=Logger.getLogger(ControllerServlet.class);

publicvoidinit(ServletConfigconfig)throwsServletException{

super.init(config);

}

publicvoidservice(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{

StringcommandCP=null;Stringview=null;

commandCP=request.getParameter(“ParameterActionCommand”);

if(commandCP!=null){

//Addedsecuritytoavoidmalinvocationofthecommands.

StringStrCommandClass=“com.bis.cp.”+commandCP+“CP”;

try{

ClassmyClass=Class.forName(StrCommandClass);

BisCommandbisCommand=(BisCommand)myClass.newInstance();

view=bisCommand.execute(request,response);

if(view==null||view.trim().equalsIgnoreCase(””)){

view=“BisError”;//Adderrormessageinsessionanddisplaythatinthejsp.

logger.debug(“Anullvaluereturnedforview”);

}

RequestDispatcherrequestDispatcher=request.getRequestDispatcher(“/BisHome.jsp?prmDynInclPage=”+view);

requestDispatcher.forward(request,response);

}catch(ClassNotFoundExceptioncnfe){

logger.error(cnfe.getMessage());

}catch(InstantiationExceptioninse){

logger.error(inse.getMessage());

}catch(Exceptionexcep){

logger.error(excep.getMessage());

}

}

else{

logger.fatal(“Actioncommandisnull”);

}

}

}

Theservicemethodperformsthefollowingtasks:

Getstherequestcommandfromtherequestparameter.

Loadsthecommandprocessorclasspertainingtothecommand.

Createsaninstanceofthecommandprocessorandinvokestheexecutemethod.

Forwardstheviewreturnedtothebrowser.

ItismandatoryforthecommandprocessortoimplementBisCommandinterfacetobequalifiedasacommandprocessor.Theexecutemethodisinvokedusingthereferenceoftheinterface(BisCommand)andnotspecificcommandprocessorclass.Itisthepolymorphicfeatureofjavawhichinvokestheexecutemethodofthespecificcommandprocessorobjectinquestion.ThisisthereasonwhyeachcommandprocessormusthavetoimplementtheBisCommandinterface.Thisisoneofthebestexampleforlatebindingandpolymorphicfeaturesinjavalanguage.

IfthecommandisAddStudent,AddStudentCPisloadedandexecutemethodisinvoked.TheAddStudentCPimplementsBisCommandinterfacewhichhastheexecutemethod.SinceAddStudentCPimplementsBisCommandithastoprovideimplementationforexecutemethodpertainingtoaddingastudent.TheobjectofAddStudentCPwhichimplementsBisCommandisreferencedviatheBisCommandinterfacereference.Similarly,ifitisothercommand,therespectiveclassisloadedandexecutemethodofthecommandprocessorclassisinvoked.Thisisoneofthebestexampleofusageofinterfacereferencetoexploitruntimedynamicpolymorphicfeatureofthejavaprogramminglanguage.

AjaxControllerServlet.javapackagecom.bis.servlet;importcom.bis.cp.BisCommand;

importjava.io.IOException;

importjava.io.PrintWriter;

importjavax.servlet.ServletConfig;

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importorg.apache.log4j.Logger;

publicclassAjaxControllerServletextendsHttpServlet{

privatestaticfinalStringCONTENT_TYPE=“text/html;charset=windows-1252”;staticLoggerlogger=Logger.getLogger(AjaxControllerServlet.class);

publicvoidinit(ServletConfigconfig)throwsServletException{super.init(config);

}

publicvoidservice(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{

response.setContentType(CONTENT_TYPE);PrintWriterout=response.getWriter();StringstrAjaxResponseText=””;StringcommandCP=null;commandCP=request.getParameter(“ParameterActionCommand”);if(commandCP!=null){if(!(commandCP.trim().equalsIgnoreCase(””))){//Addedsecuritytoavoidmalinvocationofthecommands.StringStrCommandClass=“com.bis.cp.”+commandCP+“CP”;try{ClassmyClass=Class.forName(StrCommandClass);BisCommandbisCommand=(BisCommand)myClass.newInstance();strAjaxResponseText=bisCommand.execute(request,response);

}catch(ClassNotFoundExceptioncnfe){

logger.error(cnfe.getMessage());

}catch(InstantiationExceptioninse){

logger.error(inse.getMessage());

}catch(Exceptionexcep){

logger.error(excep.getMessage());

}

}

else{

logger.fatal(“ActionCommandismissing.”);}}

else{

logger.fatal(“ActionCommandisnull.”);

}

out.println(strAjaxResponseText);

out.close();

}

}

Theservicemethodperformsthefollowingtasks:

Getstherequestcommandfromtherequestparameter.

Loadsthecommandprocessorclasspertainingtothecommand.

Createsaninstanceofthecommandprocessorandinvokestheexecutemethod.

ReturnstheAjaxResponseTexttothebrowser.

ThedifferencebetweentheAjaxControllerServletandtheControllerServletisthatthecontrollerservletreturnsaviewviaajsppagewhereastheajaxcontrollerservletreturnsaresponsetextonly.BothoftheseservletsbelongtotheBISMVCFrameworkonededicatedfortheregularhttprequestsandtheotherforajaxrequests.

TheCommandProcessors

Forthesampleapplicationandforourframework,thecommandprocessorsarejavaclassesthatextendBisCPclassandimplementBisCommandinterface.TheBisCPisaconcreteclasswithasetofvariables.TheBisCommandinterfacehasonlyonemethodandthatistheexecutemethod.

Thefollowingclassdiagramshowsallthecommandprocessorclassesusedinoursampleapplication.ItalsoshowstherelationshipbetweentheseclassesandtheframeworkartifactsBisCPandBisCommand.

BisCP.java

packagecom.bis.cp;

publicclassBisCP{

publicBisCP(){

super();

}

protectedbooleanisProcessSuccessful;protectedjava.lang.StringstrSuccessNavigation;protectedjava.lang.StringstrNextNavigation;protectedjava.lang.StringstrErrorMessage;protectedjava.lang.StringstrAjaxResponseText;

}

TheBisCP.javaclasshasonlyvariableswhichareusedinthecommandprocessorclassesthatisthesubclassesofBisCPclass.Thevariablenamesusedareselfexplanatory.

BisCommand.java

packagecom.bis.cp;

publicinterfaceBisCommand{

publicabstractStringexecute(javax.servlet.http.HttpServletRequestrequest,javax.servlet.http.HttpServletResponseresponse);

}

Thisinterfacehasonlyonemethodandthatisexecutemethod.Theimplementingcommandprocessorclassimplementsthebusinesslogicpertainingtothespecificcommandprocessorfortheexecutemethod.Notethat,itismandatorytoimplementthisinterfaceinordertoqualifyaclassasacommandprocessor.Thisisonesuchexampleofcompliancesrequirementswhenworkingwithaparticularframework.ForBisMVCFramework,acommandprocessormustimplementBisCommandinterface.Otherwise,theexecutemethodofthespecificcommandprocessorwillfailtobeexecutedpolymorphicallywithintheservicemethodofthecontrollerservlet.

TheServiceClasses

Thejoboftheserviceclassesistoimplementtheservicesi.e.thebusinesslogic.Theseclassesorchestrateandimplementthevariousactionsrequiredforausecase.Fore.g.addstudentserviceclass,insertsthreerecordstothreedifferenttablesinthedatabase.Thecommandprocessoronlyinvokestheprocessaddstudentmethodintheserviceclass.Thismethodinturninvokesmultiplemethods,takescareoftransactionalrequirements,interactswiththedatabaseusingdatabaseutilityclassesandgetsthetaskdone.Thecommandprocessorisbasicallyaclientfortheseclassestheyrequestforservicesfromtheservicesclasses.Theservicesclassesprovidetheservicestotheirclient.Thesearereusablecomponents.

TheservicesclassesinourapplicationandframeworkimplementsBisServiceinterface.Notethat,thisisnotamandatoryrequirement.Thisisjusttoprovideascalabilityoptionincasewewanttoaddcommonservicesfunctionalityinfutureversions.TheBisServiceinterfaceasofnowhasonlyonemethodwhichprovidesthenameoftheclassforthecurrentserviceinstance.

Thefollowingclassdiagramsshowsalltheservicesusedinourapplication.

BisService.java

packagecom.bis.session;

publicinterfaceBisService{

publicStringgetServiceName();

}

Theimplementingclassprovidesit’snamebyimplementingthismethod.

TheJavaBeans

Thesebeansareplainjavaclasseswithprivatefieldsandtheirpublicgetterandsettermethods.Allthebeansimplementserializableinterfaceviatheframeworkclasshierarchy.AllthebeansusedintheapplicationeventuallyextendtheclassBisBeanwhichimplementsSerializableinterface.

StudentBean.java

Thisbeanholdsallthegenericsforthestudentrelatedinformation.Alltheotherbeansthatrequirethesefieldsextendthisbean.ThestudentbeaninturnextendsBisBean.

packagecom.bis.beans;

publicclassStudentBeanextendsBisBean{

publicStudentBean(){

super();

}

privatejava.lang.StringstudentId;privatejava.lang.StringfullName;privatejava.lang.Stringgrade;privatejava.lang.Stringsection;privatejava.lang.StringfirstName;privatejava.lang.StringmiddleName;privatejava.lang.StringlastName;

publicvoidsetStudentId(StringstudentId){this.studentId=studentId;}

publicStringgetStudentId(){returnstudentId;}

publicvoidsetFullName(StringfullName){

this.fullName=fullName;

}

publicStringgetFullName(){

returnfullName;

}

publicvoidsetGrade(Stringgrade){

this.grade=grade;

}

publicStringgetGrade(){

returngrade;

}

publicvoidsetSection(Stringsection){

this.section=section;

}

publicStringgetSection(){

returnsection;

}

publicvoidsetFirstName(StringfirstName){

this.firstName=firstName;

}

publicStringgetFirstName(){

returnfirstName;

}

publicvoidsetMiddleName(StringmiddleName){

this.middleName=middleName;

}

publicStringgetMiddleName(){

returnmiddleName;

}

publicvoidsetLastName(StringlastName){

this.lastName=lastName;

}

publicStringgetLastName(){

returnlastName;

}

}

BisBean.java

packagecom.bis.beans;

importjava.io.Serializable;

publicclassBisBeanimplementsSerializable{

publicBisBean(){

super();

}

}

Allthebeansintheapplicationextendsthisbean.Itismandatorytoextendsthisbeaneitherdirectlyorindirectlytobequalifiedasabean.Theapplicationcurrentlydoesn’texchangebeaninstancebyvaluebutfortheapplicationtobescalableinthefutureversionsthisismandated.Generallyjavabeansarepersistableandhencetheyhaveto

implementserializableinterface.

TheUtilityClasses

Wehavethreeutilityclassesusedacrosstheapplicationforvariouscommonobjectives.TheseclassesareBisUtility,DatabaseServiceandBisConstants.Inthis,BisUtilityandDatabaseServiceareconcretejavaclassesandBisConstantsisajavainterface.

Bisutility.java

packagecom.bis.utility;

importjava.util.Properties;importjava.util.StringTokenizer;importjavax.mail.Message;importjavax.mail.MessagingException;importjavax.mail.Session;importjavax.mail.Transport;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeMessage;importorg.apache.log4j.Logger;

publicclassBisUtility{staticLoggerlogger=Logger.getLogger(BisUtility.class);

publicBisUtility(){

super();

}

publicstaticStringBuffergenerateStudentId(StringstrStdFirstName,StringstrStdLastName,String

strMotFirstName,StringstrFatFirstName,StringstrStdDob){

StringBuffersbStdId=newStringBuffer();

StringBuffersbDob=null;

try{

if(strStdFirstName!=null&&!(strStdFirstName.trim().equalsIgnoreCase(””))){

sbStdId.append(strStdFirstName.substring(0,2));

}else{

logger.error(“Failedtogeneratestudentid:Invalidfirstname”);

}

if(strStdLastName!=null&&!(strStdLastName.trim().equalsIgnoreCase(””))){

sbStdId.append(strStdLastName.substring(0,2));

}else{

logger.error(“Failedtogeneratestudentid:Invalidlastname”);

}

if(strMotFirstName!=null&&!(strMotFirstName.trim().equalsIgnoreCase(””))){

sbStdId.append(strMotFirstName.substring(0,2));

}else{

logger.error(“Failedtogeneratestudentid:Mother’sfirstnameisinvalid”);

}

if(strFatFirstName!=null&&!(strFatFirstName.trim().equalsIgnoreCase(””))){

sbStdId.append(strFatFirstName.substring(0,2));

}else{

logger.error(“Failedtogeneratestudentid:Father’sfirstnameisinvalid”);

}

if(strStdDob!=null&&!(strStdDob.trim().equalsIgnoreCase(””))){

StringTokenizersTokenizer=newStringTokenizer(strStdDob,“-“);

StringstrYear=sTokenizer.nextToken();

StringstrMonth=sTokenizer.nextToken();

StringstrDay=sTokenizer.nextToken();

sbDob=newStringBuffer();

sbDob.append(strDay);

sbDob.append(strMonth);

sbDob.append(strYear);

if(sbDob.length()==8){

sbStdId.append(sbDob);

}else{

logger.error(“Failedtogeneratestudentid:Invaliddateofbirth”);

}

}else{

logger.error(“Failedtogeneratestudentid:Invaliddateofbirth”);

}

if(sbStdId.length()!=16){

logger.error(“Failedtogeneratestudentid:inappropriatesize”);

}

}catch(Exceptione){

logger.error(e.getMessage());

sbStdId=null;

}

returnsbStdId;

}

publicstaticvoidsendMail(StringstrSub,StringstrText){

StringstrTo=“yousuf.baig@gmail.com”;

StringstrFrom=“yousuf.baig@yahoo.com”;

StringstrHost=“localhost”;

intinPort=25;

Propertiesproperties=System.getProperties();

properties.setProperty(“mail.smtp.host”,strHost);

properties.put(“mail.smtp.auth”,“false”);

properties.put(“mail.smtp.starttls.enable”,“true”);

properties.put(“mail.smtp.port”,inPort);

Sessionsession=Session.getDefaultInstance(properties);

try{

MimeMessagemessage=newMimeMessage(session);

message.setFrom(newInternetAddress(strFrom));

message.addRecipient(Message.RecipientType.TO,newInternetAddress(strTo));

message.setSubject(strSub);

message.setText(strText);

Transport.send(message);

}catch(MessagingExceptionmex){

logger.error(mex.getMessage());

}

}

}

ThegenerateStudentIdmethodperformsthefollowingtasks:

Thismethodgeneratesauniquestudentidforagivenstudentfromthestudent’sfirstname,student’slastname,student’smother’sfirstname,student’sfather’sfirstnameandstudent’sdateofbirth.

Letssplitupanexamplestudentid:MyFaAsYo12042004

My-firsttwodigitsofstudent’sfirstnameMyiesha.

Fa-firsttwodigitsofstudent’slastnameFatima.

As-firsttwodigitsofstudent’smother’sfirstnameAsiya.

Yo-firsttwodigitsofstudent’sfather’sfirstnameYousuf.

12042004-student’sdataofbirthinDDMMYYYY

ThegenerateStudentIdmethodtakesalltheseinputsandreturnsthegeneratedstudentidaspertherequirementsabove.

Though,adatabasesequencecanbeusedtoassignauniquestudentidforeachstudent.Thisapproachistakentomakesurethattheidcanberememberedwiththeknownalgorithm.Thisstudentidmayhavearareconflictandinthatcase,theadditionofbirthtimeoranyothersuchattributewillmakeitmoreuniqueandconflictfree.

ThesendMailmethodperformsthefollowingtasks:

ThismethodisusedforsendingsimpleSMTPmail.

Inproductionreadyapplications,theseemailpropertiesaregenerallyfetchedfromthe

applicationpropertiesfile.Incasethehostnamechanges,thesupportteamwillonlyupdatethehostnameorIPaddressinthepropertiesfileandredeploytheapplicationtofetchtheupdatedhost.Inoursampleapplication,sinceweareworkingverycloselywiththecode,thisisdirectlyaddedtothemethoditselfforquicklearningpurpose.Inseriousapplications,therecommendapproachistocreateapplicationpropertiesfileandfetchthesepropertiesfromthatfile.

DatabaseService.java

packagecom.bis.db;

importcom.bis.utility.BisConstants;

importjava.sql.Connection;

importjava.sql.ResultSet;

importjava.sql.SQLException;

importjava.sql.Statement;

importjavax.naming.Context;

importjavax.naming.InitialContext;

importjavax.naming.NamingException;

importjavax.sql.DataSource;

importorg.apache.log4j.Logger;

publicclassDatabaseService{

privatestaticDataSourcedataSource=null;

privatestaticConnectionconnection=null;

staticLoggerlogger=Logger.getLogger(DatabaseService.class);

privatestaticvoidlookUpDataSource(){if(dataSource==null){

try{

ContextinitialContext=newInitialContext();

ContextenvContext=(Context)initialContext.lookup(“java:/comp/env”);

if(initialContext!=null){

dataSource=(DataSource)envContext.lookup(BisConstants.BisDataSource);

}else{//initialcontextisnull,throwexception.

logger.error(“Initialcontextisnull”);

}

}catch(NamingExceptionne){

logger.error(“Failedtolookupdatasource.”+ne.getMessage());

}

}

}

publicDatabaseService(){

}

publicstaticvoidreleaseDBConnection(){

if(connection!=null){

try{

connection.close();

}catch(SQLExceptionsqle){

logger.error(sqle.getMessage());

}

}

}

publicstaticvoidcloseDBResouces(Statementstatement,ResultSetresultSet){

try{

if(resultSet!=null){

resultSet.close();

}

if(statement!=null){

statement.close();

}

}catch(SQLExceptionsqle){

logger.error(sqle.getMessage());

}

}

publicstaticConnectiongetDBConnection(){

if(dataSource==null){

lookUpDataSource();

}

try{

if(connection==null||connection.isClosed()){

connection=dataSource.getConnection();

}

}catch(SQLExceptionsqle){

logger.error(sqle.getMessage());

}

returnconnection;

}

}

ThelookUpDataSourcemethodperformsthefollowingtasks:

CreatestheinitialcontextandperformsJNDIlookupforBisdatasource.

NotethatthatdatasourcenamespecifiedintheBisConstantsinterfacemustbecreatedontheserverpriortothedeploymentoftheapplicationwarfile.Otherwisethelookupwillfailandalloperationsrelatedtodatabasewillnotwork.

ThereleaseDBConnectionmethodperformsthefollowingtasks:

Closesthedatabaseconnection.

ThecloseDBResoucesmethodperformsthefollowingtasks:

Closestheresultsetandstatement.

ThegetDBConnectionmethodperformsthefollowingtasks:

CallslookUpDataSourcemethodifthedatasourceisnull.

Getsthedatabaseconnectionfromthedatasourceandreturnsit.

BisConstants.java

Thisisasimplejavainterfacewhichisusedforholdingconstantvalues.packagecom.bis.utility;

publicinterfaceBisConstants{

publicstaticfinalStringBisDataSource=“jdbc/bisDataSource”;

}

Anychangeinvalueofthevariablesinthisinterfaceneedsrecompilationofthisinterface.Dependingontherequirementseitheraninterfacecanbeusedorapplicationpropertiesfilecanbeused.Theotherapproachistofetchtheconstantvaluesfromadatabasetable.

Thedesignerofthewebapplicationhastotakemultiplefactorsintoaccountforaspecificrequirementsortypeofapplicationtomakeasubjectivedesigndecision.Inoursampleapplicationweareusinganinterfaceaswellasadatabasetablewithpropertyandvalues.Thisispurelywithanintensiontolearnvariouspragmaticapproachestoaccessvariablesthatseldomchange.

TheJavaServerPages

JSPisaviewtechnologywhichaddsdynamismtostatichtmlorothermarkuplanguage.JSPsaregenerallyusedasaviewwithdynamicjspcapabilitiesalongwithstaticstandardhtmltags.Thecontentandpresentationcanbedynamicallyaddedtoawebpageattheserversidebasedontherequirements.Thismakesjsptechnologyverypowerfulandusefulforbuildingwebapplications.Thecomputationalpowerofjavaclubbedwiththepresentationcapabilityofhtmlmakesajspaperfectchoicefortheviewlayerofwebapplications.

InoursampleBIS-SMSwebapplicationweuseonlyjspsfortheviewlayer.Theheader,footerandthemenusremainconstantpartoftheviewbetweenloginandlogoutsession.ThedesignforourviewhasonepagetemplatecalledBisHome.jsp.Theuserisalwaysonthispageduringthesession.Thejsppagehasallthecommonpresentationpartalongwithadynamicregionwherethevariouspagesaredisplayedasanincludebasedontheuserinteraction.Pleasereferchapter5formoredetailsonthedynamicandstaticviewpartsofthepage.

Theviews(jsppages)foralltheusecasesaredynamicallyincludedintheBisHome.jsppage.Theindividualjsppagesfortheusecasesdoesnotholdanycodeortagsforthecommonparti.e.fortheheader,footeretc.TheBisHome.jsphasallthestaticviewpartandgivenanareaforthedynamicpage.Thisareaiscalledthedynamicregionandinthisregionthevariousjsppagesbasedontheusecaseinquestionaredisplayed.

TheBisHome.jsppagewithoutanyjspincludedwithdynamicregionisshowninthebelowfigure.Here,allthecommonviewpartliketheheader,footer,menusetcaredisplayedforallthepages.Onlythedynamicpartchanges.Fore.g.forthegetstudentdetailsusecasethedynamicpartwilldisplayStudentDetails.jsppagewithinthedynamicregion.

Plus(+)

IsEqualTo(=)

TheviewonlyfromtheStudentDetails.jspisasshowninthefigureabove.TheBisHome.jsppagetemplateplustheStudentDetails.jspviewwillprovidethefinalviewforthecompletepagedisplayasshownabove.

CommonsView+DynamicView=CompletePageView.

BisHome.jsp

Here’sthesourcecodeoftheBisHome.jsppage.Thishastheheaderwiththemenus,thefooterandthejsp:includetagforthedynamicjsppagetobeincluded.

<!DOCTYPEHTMLPUBLIC“-//W3C//DTDHTML4.01Transitional//EN”“http://www.w3.org/TR/html4/loose.dtd”>

<%@pagecontentType=“text/html;charset=windows-1252”%>

<%@pageimport=“java.util.Date”%>

<%

StringstrDynIncPage=“BisError.jsp”;

strDynIncPage=request.getParameter(“prmDynInclPage”)+“.jsp”;

%>

<html>

<head>

<metahttp-equiv=“Content-Type”content=“text/html;charset=windows-1252”/>

<title>BaigInternationalSchool</title>

<linkrel=“stylesheet”type=“text/css”href=“resources/css/BISStyle.css”></link>

<scriptsrc=“resources/js/BISScript.js”></script>

</head><body>

<tableborder=“0”cellpadding=“0”cellspacing=“0”width=“100%”height=“99%”>

<trbgcolor=“White”>

<td>

<tableborder=“0”cellpadding=“0”cellspacing=“0”width=“100%”>

<trheight=“70”>

<tdalign=“left”valign=“bottom”width=“15%”>

&nbsp;&nbsp;&nbsp;&nbsp;

<%=newDate()%>

</td>

<tdalign=“center”valign=“middle”width=”*”>

BaigInternationalSchool

</td>

<tdalign=“right”valign=“bottom”width=“15%”>

<%

out.println(request.getRemoteUser());

%>

&nbsp;&nbsp;|&nbsp;&nbsp;

<ahref=“bissecurityservlet”>Logout</a>

&nbsp;&nbsp;&nbsp;&nbsp;

</td>

</tr>

</table>

</td>

</tr>

<trvalign=“top”>

<td>

<tableborder=“0”cellpadding=“0”cellspacing=“0”width=“100%”>

<tr>

<tdrowspan=“3”align=“left”>

<divid=“cssmenu”>

<ul>

<liclass=‘has-sub’>

<ahref=‘BisControllerServlet?ParameterActionCommand=BisDashboard’>

<span>Home</span>

</a>

</li>

<liclass=‘has-sub’>

<ahref=’#’>

<span>Students</span>

</a>

<ul>

<li>

<ahref=“BisControllerServlet?ParameterActionCommand=GetStudentDetails”><span>Details</span></a>

</li>

<li>

<ahref=“BisControllerServlet?ParameterActionCommand=GetStudentAcademics&sem=1”>

<span>Sem-IResults</span></a>

</li>

<li>

<ahref=“BisControllerServlet?ParameterActionCommand=GetStudentAcademics&sem=2”>

<span>Sem-IIResults</span></a>

</li>

<li>

<ahref=“BisControllerServlet?ParameterActionCommand=GetStudentAttendance&sem=1”><span>Sem-IAttendance</span></a>

</li>

<li>

<ahref=“BisControllerServlet?ParameterActionCommand=GetStudentAttendance&sem=2”><span>Sem-IIAttendance</span></a>

</li>

<li>

<ahref=“BisControllerServlet?ParameterActionCommand=GetStudentFees”><span>Fees</span></a>

</li>

</ul>

</li>

<liclass=‘has-sub’>

<ahref=’#’>

<span>Admin</span></a>

<ul>

<li>

<ahref=“BisControllerServlet?ParameterActionCommand=AddStudent”>

<span>AddStudent</span></a>

</li>

<liclass=‘last’>

<ahref=“BisControllerServlet?ParameterActionCommand=EditStudent”>

<span>EditStudent</span></a>

</li>

<liclass=‘last’>

<ahref=“BisControllerServlet?ParameterActionCommand=ManageResult”>

<span>ManageResult</span></a>

</li>

<liclass=‘last’>

<ahref=“BisControllerServlet?ParameterActionCommand=ManageAttendance”>

<span>ManageAttendance</span></a>

</li>

<liclass=‘last’>

<ahref=’\bis\jsp\ManageStudentFees.html’>

<span>ManageFees</span></a>

</li>

</ul>

</li><liclass=‘has-sub’>

<ahref=’#’>

<span>Reports</span></a>

<ul>

<li>

<ahref=“BisControllerServlet?ParameterActionCommand=GetReportByClass”>

<span>Class</span></a>

</li>

<li>

<ahref=’\bis\jsp\ReportsBus.html’>

<span>Bus</span></a>

</li>

<li>

<ahref=’\bis\jsp\ReportsFees.html’><span>Fees</span></a>

</li>

</ul>

</li>

<liclass=‘has-sub’>

<ahref=’#’>

<span>Help</span></a>

<ul>

<li>

<ahref=’\bis\jsp\ResultsLegend.html’>

<span>Legend</span></a>

</li>

<li>

<ahref=’#’>

<span>FAQs</span></a>

</li>

<li>

<ahref=’#’>

<span>HolidayCalender</span></a>

</li>

<li>

<ahref=’#’>

<span>EscalationMatrix</span></a>

</li>

<li>

<ahref=’#’>

<span>FeeStructure</span></a>

</li>

</ul>

</li>

</ul>

</div>

</td>

</tr>

</table>

</td>

</tr>

<tr>

<td>

<jsp:includepage=”<%=strDynIncPage%>”flush=“true”/>

</td>

</tr>

<tr>

<tdcolspan=“2”>

&nbsp;

</td>

</tr>

<tr><td>&nbsp;</td></tr>

<trid=“trbgred”>

<tdalign=“center”colspan=“2”>©copyright:2015,MirzaYousufAhmedBaig,BuildWebApplications

withJava</td>

</tr>

</table>

</body>

</html>

Alltheotherjsppagesusedintheapplicationaredetailedinthechapterforusecasesimplementation.

Log4j

Loggingisamechanismtorecordtheactivitiesperformedbyanexecutingsoftwareprogram.Whenasoftwareprogramisexecutedlinebylineitaccomplishescertainintendedtasks.Duringtheexecution,theprogramlogsthesuccess,failures,importantactionoranyothersignificantinformationintoafile.Thisfileknownasalogfileisusedtomonitorthehealthaswellasthejobofthesoftware.Themostcommonusageofloggingistoidentifysystemandbusinesserrorsandithelpsinfixingthem.Logginghelpsinsmoothlyrunningthesoftwaresystembyprovidingtherequiredinformationtothesupportteam.Inabroadersense,logginghelpsalotinsoftwaresystemgovernance.

InoursampleapplicationweareusingLog4j.Apachelog4jisaloggingutilityanditprovidesreadymademechanismtoenablelogginginjavaapplicationswithlittleconfigurations.

Formoredetailsonloggingimplementationinoursampleapplication,pleasereferthechapteronlogging.

15IMPLEMENTINGUSECASES

Ausecaseisanendtoendscenarioforaparticularactorinteractionwiththesysteminordertoaccomplishatask.Thisisalistofoneormorestepsbetweenanactorwithaparticularrole(s)andthesystemtoachieveaspecifictask.Theactorisgenerallyahumanbutitcouldalsobeanexternalsystemoraneventtriggeredbytime.

Withrespecttoourapplication,ausecaseisaninteractionbetweentheuserandBIS-SMSwebapplicationinordertoachieveaparticulargoal.Theuserinourcasecouldbeateacher,adminoraclerk.Fore.g.theuserwithadminrolecanaddanewstudenttotheapplication.Thegoalinthiscaseistoaddanewstudenttothesystem.Theactorisahumanuserwhoholdstheadminrole.Thisusecasehasmanysteps:firstidentifytheroleoftheauthenticateduserthenauthorizehim/herwiththeprivilegetoaddastudenttothesystem.Thenextstepincludesprovidingtheuseraformtoaddthenewstudentdetails.Andfinally,validatetheformcontentsenteredbytheuserandtheninsertthedatatothedatabase.Hence,intheaboveexampleusecasewehaveseentheactor,thesteps,thegoal.Inordertoaddmoreclaritythisusecasecanbesupportedwithausecasediagramwhichconveystherequirementpictoriallyforeasierunderstandingandclarityfortheusecase.

Asoftwareapplicationconsistsof“n”numberofusecases.Theseusecases(withaUMLusecasediagram)provideclarityforrequirements.Helpindesigningandbuildingthesoftware.Helpintestingthesoftware.Usecaseshelpthroughoutthelifecycleofsoftwaredevelopment.

Inthischapter,wewilldefineanddetailalltheusecasesofoursampleapplication.Wewillthenimplementtheseusecasesandfinallywewillunittestthem.Letsbeginwiththelistofalltheusecasesforourapplication.

1. Authenticateuser.2. Authorizeuserandrenderdashboardbasedonrole.3. Loadstudent.4. Getstudentdetails.5. Getstudentresults.6. Getstudentattendance.7. Getstudentfeesstatus.

8. Managestudentattendance.9. Addstudent.

10.Getreportbyclass.

UseCase:Authentication.

RequirementsSpecificationReference:R1

PrototypeReference:P1

Prerequisite:Theusermusthaveanaccounttoaccessthesystem.

Aspertheuserrequirementspecificationsandprototypeweneedtobuildaloginpageforthisusecase.Thisfallsunderthecategorycalledformbasedauthentication.Inthiscategory,aformwithuseridandpasswordissubmittedtoauthenticateauser.TheUIisverysimpleforthisusecasewithjustonepagehavingtwofieldsandaloginbutton.Pleasereferchapter16formoredetailsonsecuringapplicationswithApacheTomcat.Wehaveonlyonejsppageforthisusecase.

BisLogin.jsp

InordertousecontainermanagedsecuritywithApacheTomcat8weneedtousethefollowingfieldnamesandformaction.Otherthanthis,theloginpageismereahtmldocumentwiththeUIaspertheprototype.

<formid=“frmBisLogin”method=“POST”action=“j_security_check”>

Theactionattributemustbe“j_security_check”.

<inputtype=“password”name=“j_password”size=“20”>

Thepasswordtagmustbenamed“j_password“.

<inputtype=“text”name=“j_username”size=“20”>

Theusertextfieldmustbenamed“j_username”.

<!DOCTYPEHTMLPUBLIC“-//W3C//DTDHTML4.01Transitional//EN”“http://www.w3.org/TR/html4/loose.dtd”>

<%@pagecontentType=“text/html;charset=windows-1252”%>

<html>

<head>

<title>BISLogin</title>

<style>

body{

background-color:#BBBBBB;

}

#dashboardlink{

color:Blue;

font-size:large;

}

#trbgred{

color:white;

background-color:red;

}

#bigwhtxt{

color:White;

font-size:x-large;

}

#regfont{

color:white;

}

#headingfont{

color:Red;

font-size:xx-large;

font-style:bold;

}

#headingtxt{

color:Red;

font-size:large;

}

#redFontWhiteBg{

color:red;

background-color:White;

}

#whiteBg{

background-color:White;

font-size:large;

}

#submitButton{

color:red;

background-color:White;

font-size:large;

}

#clred{

color:red;

}

</style>

</head>

<bodybgcolor=”#BBBBBB”>

<formid=“frmBisLogin”method=“POST”action=“j_security_check”>

<tableborder=“1”cellpadding=“0”cellspacing=“0”width=“100%”>

<trbgcolor=“White”>

<td>

<tableborder=“0”cellpadding=“0”cellspacing=“0”width=“100%”bgcolor=“White”>

<trheight=“70”>

<tdrowspan=“3”align=“center”>

<fontid=“headingfont”size=“7”>

BaigInternationalSchool

</font>

</td>

</tr>

</table>

</td>

</tr>

<tr>

<td>

<tableborder=“0”cellpadding=“1”cellspacing=“1”width=“100%”>

<trheight=“60”><tdcolspan=“3”>&nbsp;</td></tr>

<tr>

<tdwidth=“25%”>

&nbsp;

</td>

<tdwidht=”*”>

<tableborder=“0”cellpadding=“5”cellspacing=“5”width=“100%”bgcolor=“White”>

<tr>

<tdcolspan=“2”id=“trbgred”align=“left”>

&nbsp;&nbsp;

Signin

</td>

<tr>

<tdcolspan=“2”align=“left”>

&nbsp;

</td>

</tr>

<tr>

<tdalign=“right”width=“50%”>

UserId

</td>

<tdwidth=”*”>

<inputtype=“text”name=“j_username”size=“20”>

</td>

</tr>

<tr>

<tdalign=“right”>

Password

</td>

<td>

<inputtype=“password”name=“j_password”size=“20”>

</td>

</tr>

<tr>

<tdalign=“center”colspan=“2”height=“50”>

<inputtype=“submit”value=”Login”id=“sbmt”>

</td>

</tr>

<tr>

<tdcolspan=“2”align=“right”>

<ahref=””>

Forgotpassword

</a>

&nbsp;&nbsp;

</td>

</tr>

<tr>

<tdalign=“right”colspan=“2”id=“trbgred”>&nbsp;</td>

</tr>

</table>

</td>

<tdwidth=“25%”>

&nbsp;

</td>

</tr>

<trheight=“30”><tdcolspan=“3”>&nbsp;</td></tr>

</table>

</td>

</tr>

<trid=“trbgred”>

<tdrowspan=“3”align=“center”>

<fontid=“regfont”>

©copyright:2015,MirzaYousufAhmedBaig,BuildWebApplicationswithJava

</font>

</td>

</tr>

</table>

</form>

</body>

</html>

Thisconcludestheimplementationofthisusecase.Informbasedauthenticationmechanism,theimplementershavetheluxurytohavewhateverUIclientwants.Theonlycompulsionishavingtheabovedescribedfieldnamesandformactionpoint.Notethatforusingcontainermanagedsecurityweneedtofollowthedocumentationoftheparticularserverbeingused.Here,wehaveusedApacheTomcatandhencewehaveusedj_username,j_passwordandj_security_check.

UseCase:Authorization.

RequirementsSpecificationReference:R2

PrototypeReference:P2

Prerequisite:Theusermustbeauthenticatedandmusthaveatleastoneassignedrole.

Pleasereferchapter16fordetailsontheconfigurationpart.Inthisusecaseimplementationourobjectiveistorenderaccesslinksinthedashboardpageandglobalnavigationmenubasedontherole.ForthiswewillhaveacloserlookatthesourcecodeoftwojsppagesBisHome.jspandBisDashboard.jsp.

BisDashboard.jsp

Thisisthelandingpageofthesamplewebapplicationpostsuccessfulauthentication.Inthisdashboardpagethelinksaredisplayedbasedontherole(s)oftheloggedinuser.

<!DOCTYPEHTMLPUBLIC“-//W3C//DTDHTML4.01Transitional//EN”“http://www.w3.org/TR/html4/loose.dtd”>

<%@pagecontentType=“text/html;charset=windows-1252”%>

<%@pageimport=“com.bis.beans.StudentDetailsBean”%>

<%@pageimport=“java.util.Hashtable,java.util.Enumeration”%>

<%

StudentDetailsBeanstudentDetailsBean=null;

if(session!=null){

studentDetailsBean=(StudentDetailsBean)session.getAttribute(“studentDetailsBean”);

}

%>

<html>

<head>

<metahttp-equiv=“Content-Type”content=“text/html;charset=windows-1252”/>

<title>BaigInternationalSchool-Dashboard</title>

<linkrel=“stylesheet”type=“text/css”href=“resources/css/BISStyle.css”></link>

<scriptsrc=“resources/js/BISScript.js”></script>

</head>

<body>

<formid=“frmDashboard”name=“frmDashboard”action=“BisControllerServlet”method=“POST”>

<inputtype=“hidden”name=“ParameterActionCommand”value=“BisDashboard”></input>

<tableborder=“0”cellpadding=“0”cellspacing=“0”width=“100%”>

<tr><td>&nbsp;</td></tr>

<tr>

<td>

<tableborder=“0”cellpadding=“0”cellspacing=“0”width=“100%”>

<tr>

<tdwidth=“33%”align=“center”valign=“middle”>

<tableborder=“0”cellpadding=“5”cellspacing=“0”width=“90%”bgcolor=“White”>

<tr>

<tdalign=“center”id=“trbgred”>FindStudent</td>

</tr>

<tr><td>&nbsp;</td></tr>

<tr>

<tdalign=“center”>

StudentID

&nbsp;&nbsp;

<inputtype=“text”name=“txtStdId”id=“txtStdId”size=“20”></input>

&nbsp;&nbsp;

<inputtype=“button”value=“LoadStudent”id=“btnStdDtls”onclick=“getStudentAJAX()”></input>

</td>

</tr>

<tr><td>&nbsp;</td></tr>

<tr><tdid=“trbgred”align=“center”>StudentinContext</td></tr>

<tr><td>&nbsp;</td></tr>

<tr>

<tdalign=“center”id=“headingtxt”>

<divid=“dvStdSmry”>

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getFullName());

out.print(“&nbsp;&nbsp;|”);

}

%>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getGrade());

out.print(”-“);out.print(studentDetailsBean.getSection());

out.print(“&nbsp;&nbsp;|”);

}

%>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getStudentId());

}

%>

</div>

</td>

</tr>

<tr><td>&nbsp;</td></tr>

</table>

</td>

<tdwidht=”*”align=“center”valign=“middle”>

<tableborder=“0”cellpadding=“7”cellspacing=“7”width=“95%”>

<trvalign=“top”>

<tdalign=“left”width=“50%”>

<tableborder=“0”cellpadding=“5”cellspacing=“0”width=“100%”bgcolor=“White”>

<tr>

<tdalign=“center”id=“trbgred”>StudentInformation</td>

</tr>

<tr>

<tdalign=“left”>

<ahref=”#”id=“dashboardlink”>

Studentdetails

</a>

</td>

</tr>

<tr>

<tdalign=“left”>

<%

if(request.isUserInRole(“BisTeacher”)||request.isUserInRole(“BisAdmin”)){

%>

<ahref=“BisControllerServlet?ParameterActionCommand=GetStudentAcademics&sem=1”id=“dashboardlink”>

Semester-Iresults

</a>

<%

}

else{

%>

<aid=“dashboardlink”>

Semester-Iresults

</a>

<%

}

%>

</td>

</tr>

<tr>

<tdalign=“left”>

<%

if(request.isUserInRole(“BisTeacher”)||request.isUserInRole(“BisAdmin”)){

%>

<ahref=“BisControllerServlet?ParameterActionCommand=GetStudentAcademics&sem=2”id=“dashboardlink”>

Semester-IIresults

</a>

<%

}

else{

%>

<aid=“dashboardlink”>

Semester-IIresults

</a>

<%

}

%>

</td>

</tr>

<tr>

<tdalign=“left”>

<ahref=”#”id=“dashboardlink”>

Semester-IAttendance

</a>

</td>

</tr>

<tr>

<tdalign=“left”>

<ahref=”#”id=“dashboardlink”>

Semester-IIAttendance

</a>

</td>

</tr>

<tr>

<tdalign=“left”>

<%

if(request.isUserInRole(“BisClerk”)||request.isUserInRole(“BisAdmin”)){

%>

<ahref=“BisControllerServlet?ParameterActionCommand=GetStudentFees”id=“dashboardlink”>

Fees

</a>

<%

}

else{

%>

<aid=“dashboardlink”>

Fees

</a>

<%

}

%>

</td>

</tr>

</table>

</td>

<tdalign=“left”width=”*”colspan=“2”>

<tableborder=“0”cellpadding=“5”cellspacing=“0”width=“100%”bgcolor=“White”>

<tr>

<tdalign=“center”id=“trbgred”>Administration</td>

</tr>

<tr>

<tdalign=“left”>

<ahref=”#”id=“dashboardlink”>

AddStudent

</a>

</td>

</tr>

<tr>

<tdalign=“left”>

<ahref=”#”id=“dashboardlink”>

EditStudent

</a>

</td>

</tr>

<tr>

<tdalign=“left”>

<ahref=”#”id=“dashboardlink”>

ManageResult

</a>

</td>

</tr>

<tr>

<tdalign=“left”>

<ahref=”#”id=“dashboardlink”>

ManageAttendance

</a>

</td>

</tr>

<tr>

<tdalign=“left”>

<ahref=”#”id=“dashboardlink”>

ManageFees

</a>

</td>

</tr>

<tr>

<tdalign=“left”>

&nbsp;

</td>

</tr>

</table>

</td>

</tr>

<trvalign=“top”>

<tdalign=“left”width=“50%”>

<tableborder=“0”cellpadding=“5”cellspacing=“0”width=“100%”bgcolor=“White”>

<tr>

<tdalign=“center”id=“trbgred”>Reports</td>

</tr>

<tr>

<tdalign=“left”>

<ahref=“BisControllerServlet?ParameterActionCommand=GetReportByClass”id=“dashboardlink”>

Class

</a>

</td>

</tr>

<tr>

<tdalign=“left”>

<ahref=”#”id=“dashboardlink”>

Bus

</a>

</td>

</tr>

<tr>

<tdalign=“left”>

<ahref=”#”id=“dashboardlink”>

Fees

</a>

</td>

</tr>

<tr>

<tdalign=“left”>

&nbsp;

</td>

</tr>

<tr>

<tdalign=“left”>

&nbsp;

</td>

</tr>

<tr>

<tdalign=“left”height=“27px”>

&nbsp;

</td>

</tr>

</table>

</td>

<tdwidth=”*”valign=“top”>

<tableborder=“0”cellpadding=“5”cellspacing=“0”width=“100%”bgcolor=“White”>

<tr>

<tdalign=“center”id=“trbgred”>Help</td>

</tr>

<tr>

<tdalign=“left”>

<ahref=”#”id=“dashboardlink”>

AcademicsLegend

</a>

</td>

</tr>

<tr>

<tdalign=“left”>

<ahref=”#”id=“dashboardlink”>

FAQs

</a>

</td>

</tr>

<tr>

<tdalign=“left”>

<ahref=”#”id=“dashboardlink”>

HolidayCalender

</a>

</td>

</tr>

<tr>

<tdalign=“left”>

<ahref=”#”id=“dashboardlink”>

EscalationMatrix

</a>

</td>

</tr>

<tr>

<tdalign=“left”>

<ahref=”#”id=“dashboardlink”>

FeeStructure

</a>

</td>

</tr>

<tr>

<tdalign=“left”>

<ahref=”#”id=“dashboardlink”>

Events

</a>

</td>

</tr>

</table>

</td>

</tr>

</table>

</td>

</tr>

<tr><td>&nbsp;</td></tr>

<tr>

<tdcolspan=“2”align=“center”>

<tableborder=“0”cellpadding=“5”cellspacing=“0”width=“100%”bgcolor=“White”>

<tr>

<tdalign=“center”id=“trbgred”>Announcement</td>

</tr>

<tr><td>&nbsp;</td></tr>

<tr>

<tdalign=“center”>

TheannualdayeventisscheduledforJan26,2015.

</td>

</tr>

<tr><td>&nbsp;</td></tr>

<tr><td>&nbsp;</td></tr>

</table>

</td>

</tr>

</table>

</td>

</tr>

<tr><td>&nbsp;</td></tr>

</table>

</form>

</body>

</html>

Letshaveacloserlookatthecodesnippetwhichrenderslinksbasedontherole.<tr><tdalign=“left”><%

if(request.isUserInRole(“BisTeacher”)||request.isUserInRole(“BisAdmin”)){

%>

<ahref=“BisControllerServlet?ParameterActionCommand=GetStudentAcademics&sem=1”id=“dashboardlink”>

Semester-Iresults

</a>

<%

}

else{

%>

<aid=“dashboardlink”>

Semester-Iresults

</a>

<%

}

%>

</td>

</tr>

Intheabovecodesnippet,request.isUserInRole(“BisTeacher”)checkswhethertheloggedinuserhastheroleBisTeacher.Ifyes,thecoderenderslinkfortheresults.Ifno,theuseronlyseesalabel.Wearedisplayingalabelherejusttodemonstrateforlearningpurpose.Inrealapplications,thelabelisgenerallynotshown.Thatis,theuseronlyseesthoselinkswhoseaccesstherolehasandnolabelsareshownforthosefunctionalitieswhichtheroledoesnothave.

BisHome.jsp

Thispageistheplaceholderpageforallotherpages.Thispagehasallthecommonsthatbelongtotheview.Themenu,theheaderandthefooterbelongtothispage.Inthispagethedynamicregiondisplaysvariousotherpagesbasedonuserinteraction.Pleasereferchapter14forthesourcecodeanddetailsaboutBisHome.jsppage.

Thisconcludestheimplementationofthisusecase.Forapplicationsthatdemandhigherlevelofsecurity,therolecanbeverifiedattheserversidecodeimplementationasapre-conditionbeforetheexecutionofeachusecase.

UseCase:LoadStudent.

RequirementsSpecificationReference:R3

PrototypeReference:P3

Prerequisite:Theuserhastobeloggedin.

Thisusecaseneedstobeimplementedaspertherequirementsspecificationreferenceabove.TheUIneedstobeaspertheprototypereferenceabove.NowthatwehavecompleteclarityonusecaserequirementsandUIwewillnowproceedtoimplementthisusecase.

Inordertoimplementthisusecase,weneedtofollowthearchitectureandleveragetheframework.Toachievethiswewillfirstcomeupwithdetaileddesignandthencodeit.

Theprerequisiteforthisusecaseisthattheusehastobesignedin.Theobjectiveofthisusecaseistoloadastudentintocontext.Onceastudentisloadedintocontextitisavailableinthehttpsession.Alltheotherusecasesusethestudentidfromthehttpsession.Thisistheprerequisiteusecaseformanyusecasesinthisapplication.Onthedashboardpage,theuserentersthestudentidandclicksloadstudent.Thisusecaseneedstoperformtwoaction.First,itmustdisplaythestudentcontextinformationontheloadstudentregionwithinthedashboardpage.Second,ontheserversideitmustaddthestudentidtothehttpsession.

Inthisusecase,wearesendingthestudentidandgettingbackthebasicinformationaboutthestudent(name,grade,sectionandid)forthedisplay.Theotheractionisaddingthestudentidtothesessionontheserverside.Onthebrowser,itdoesnotmakesensetosubmittheentireformandreloadtheentiredashboardpage.Oncetheuserclicksloadstudentbuttonbyenteringthestudentid,weneedtoonlysendthestudentidtotheserver.

ForsendingsuchselectivevaluestotheserverandperformingactionontheserversideandalsoreceivingasubsetofdataforthepagewithoutsubmittingtheentirepageformorwithoutreloadingtheentirepageweuseAJAX.Pleasegothroughchapter20nowformoredetailsonAJAX.Thatistheprerequisitenowtoproceedfurtheronthisusecaseimplementation.

Theuserentersstudentidandclicksloadstudent.

ThisinvokesthejavascriptfunctiongetStudentAJAX()intheBisScript.js.

TheBisAjaxControllerServletisinvokedontheserver.

IntheservicemethodtheactioncommandparametervalueisreadwhichisLoadStudent

TheexecutemethodforthecommandprocessorpertainingtoLoadStudentisinvoked.

Thebusinesslogicpertainingtothiscommandprocessorisexecutedandaresponsetextisreturned.

TheserverreturnstheAjaxresponseandthatresultsintheinvocationoftheAJAXcallbackfunctiononthebrowser.Also,thestudentidisaddedtothehttpsession.

Thecallbackfunctionsetstheresponsetextandtheuserseestheupdatedregionwithstudentcontextinfo.Notethatthisisjustaregionrefreshandtheentirepageisnot

reloaded.

LetsnowdesignthisusecasewithAJAX.Pleaserefertheclassdiagramsinchapter14formoredetailsabouttheclassesused.InourBISFramework,wehaveaseparatecontrollertohandallAJAXrequests.ThisiscalledAJAXControllerServlet.LetsseethesequencediagramforloadstudentusecaseimplementedusingAJAX.

Whentheuserclicksloadstudentafterenteringthestudentid.TheAjaxControllerServletisinvoked,thisservlettheninvokestheexecutemethodofLoadStudentCP.Withintheexecutemethod,wereadthestudentidenteredbytheuserasaparameter.TheStudentDetailsServiceisthanleveragedtoloadthestudent.TheloadStudentmethodwithinStudentDetailsServiceusesDatabaseServiceclassandqueriesthedatabaseforthegivenstudentid.Thereturnedvalueiscomposedasasinglestringwithstudentname,studentid,classandsection.ThisformstheAjaxResponseTextwhichisreturnedbacktothebrowser.BeforesendingbacktheAjaxResponseText,thestudentidisaddtotheHttpsession.ThebrowserdisplaysthestudentcontextonceitreceivestheAjaxResponseText.

Wenowhavethestudentincontextonthedashboardpageandstudentidinhttpsession.ThepurposeofloadstudentusecaseisnowachievedusingAJAX.Letsnowhaveacloserlookintothesourcecodefortheartifactsusedinthisusecase.

1.LoadStudentCP.java

2.StudentDetailsService.java

3.BisDashboard.jsp

4.BisScript.js

LoadStudentCP.javapackagecom.bis.cp;

importcom.bis.session.StudentDetailsService;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importjavax.servlet.http.HttpSession;

importorg.apache.log4j.Logger;

publicclassLoadStudentCPextendsBisCPimplementsBisCommand{

staticLoggerlogger=Logger.getLogger(LoadStudentCP.class);

publicLoadStudentCP(){

super();

}

publicStringexecute(HttpServletRequestrequest,HttpServletResponseresponse){

StringstrStudentId=null;

HttpSessionsession=null;

strStudentId=request.getParameter(“txtStdId”);

session=request.getSession();

if(strStudentId!=null){

try{

StudentDetailsServicestudentDetailsService=newStudentDetailsService();

strAjaxResponseText=studentDetailsService.loadStudent(strStudentId);

session.setAttribute(“StudentId”,strStudentId);

}catch(Exceptione){

logger.error(e.getMessage());

}

}

returnstrAjaxResponseText;

}

}

Theexecutemethodperformsthefollowingtasks:

Getsthestudentidfromtherequestparameter.

Getsthehttpsessionfromtherequestobject.

CreatesaninstanceofStudentDetailsServiceandcallsloadStudentmethod.

Addsthestudentidtothehttpsession.

ReturnstheAjaxresponsetext.

StudentDetailsService.java

LetsfocusonlyontheloadStudentmethodofthisjavaclass.Restofthisjavaclassisdetailedinthegetstudentdetailsusecase.

publicStringloadStudent(StringstrStudentId){

StringstrStudentSummary=””;

StringstrFirstName=””;

StringstrMiddleName=””;

StringstrLastName=””;

StringstrFullName=””;

StringstrGrade=””;

StringstrSection=””;

Connectionconnection=null;

Statementstatement=null;

ResultSetresultSet=null;

if(strStudentId!=null){

StringBuffersbQuery=newStringBuffer(“SELECTFIRST_NAME,MIDDLE_NAME,LAST_NAME,GRADE,SECTIONFROMSTUDENT_DETAILSWHERESTUDENT_ID=’”);

sbQuery.append(strStudentId+”’”);

DatabaseServicedatabaseService=newDatabaseService();

connection=databaseService.getDBConnection();

try{

statement=connection.createStatement();

resultSet=statement.executeQuery(sbQuery.toString());

resultSet.next();//Expectingonlyonerecord.

strFirstName=resultSet.getString(“FIRST_NAME”);

strMiddleName=resultSet.getString(“MIDDLE_NAME”);

strLastName=resultSet.getString(“LAST_NAME”);

strGrade=resultSet.getString(“GRADE”);

strSection=resultSet.getString(“SECTION”);

if(strFirstName!=null){

strFullName=strFirstName;

}

if(strMiddleName!=null){

strFullName=strFullName+””+strMiddleName;

}

if(strLastName!=null){

strFullName=strFullName+””+strLastName;

}

strStudentSummary=strFullName+“&nbsp;&nbsp;|&nbsp;&nbsp;”+strGrade+“-”+strSection+“&nbsp;&nbsp;|&nbsp;&nbsp;”+strStudentId;

}catch(SQLExceptionsqle){

logger.error(sqle.getMessage());

}finally{

databaseService.closeDBResouces(statement,resultSet);

databaseService.releaseDBConnection();//Releasingdatabaseconnection.

}

}

else{

logger.error(“Studentidisnull”);

}

returnstrStudentSummary;

}

TheloadStudentmethodperformsthefollowingtasks:

Cooksupadynamicqueryforagivenstudentid.

Queriesthedatabaseforbasicstudentdetails.TheDatabaseServiceclassisleveragedtoachievethis.

Buildsastringcomprisingofstudentsummary.Thisholdsname,id,classandsection.

ReturnsthestudentsummarystringasAjaxresponsetext.

BisDashboard.jsp

ThisjsppageisdescribedindetailundertheAuthorizationusecase.Here,wewilllookintoonlythesnippetwhichdealswiththeAjaxrefreshregion.

<tr>

<tdalign=“center”id=“headingtxt”>

<divid=“dvStdSmry”>

</div>

</td>

</tr>

OncetheAjaxbasedjavascriptcallbackfunctionisinvokedthedivtagwithiddvStdSmryisassignedavaluefordisplay.ThisvalueholdingthestudentsummarysentfromtheAjaxresponseisdynamicallydisplayedtotheregion.

Letslookintothejavascriptpartforthisusecase.

BisScript.js

varxmlHttpReq=false;

functiongetStudentAJAX(){

varstdId=document.getElementById(“txtStdId”).value;

varurl=“BisAjaxControllerServlet?ParameterActionCommand=LoadStudent&txtStdId=”;

url=url+stdId;

xmlHttpReq=newXMLHttpRequest();

xmlHttpReq.open(“GET”,url,true);

xmlHttpReq.send();

xmlHttpReq.onreadystatechange=getStudentAjaxCallBack;

}

functiongetStudentAjaxCallBack(){

if(xmlHttpReq.readyState==4&&xmlHttpReq.status==200){

document.getElementById(“dvStdSmry”).innerHTML=xmlHttpReq.responseText;

}

}

WehavetwoJavascriptfunctionsandonevariablefortheloadstudentviaAjaxusecase.

ThegetStudentAJAXfunctionperformsthefollowingtasks:

Readsthestudentidenteredbytheuserinthetextfield.

InitializesaURLforAjaxcontrollerservletalongwiththeparametersforloadstudentactioncommandandstudentid.

CreatesaninstanceofXMLHttpRequestformakinganAjaxcalltotheserver.

OpensagetrequestforthegivenURL.

AssignsacallbackfunctiontotheXMLHttpRequestinstancetobeinvokeduponachangeinreadystate.

AndfinallysendstheAjaxrequesttotheserver.

ThegetStudentAJAXCallBackfunctionperformsthefollowingtasks:

ValidatesthereadystateforXMLHttpRequestinstance.

Assignstheresponsetexttoinnerhtmlusingthedivtag.

Thisconcludestheusecaseforloadstudent.InthisusecasewesawhowAjaxcanbeemployedtosetastudentcontextintothesessiononserversideandthestudentinquestioncontextontheclientside.

WehaveseenthataseparatecontrollerservletisemployedforthispurposeandthatcomeswiththeBISframework.ForAjax,XMLHttpRequestisusedontheclientside.Weusedtwojavascriptfunctionstoachievethisfunctionality.Whentheuserenteredstudentidandclickedloadstudentbutton,weinvokedthejavascriptfunctiontomakeanAjaxcall.ThisjavascriptfunctionleveragedXMLHttpRequestobjectandissueanAjaxcallforagivenURLwithgivenparameters.Ontheserverside,theAjaxcontrollerservletinvokedtheexecutemethodforloadstudentcommandprocessor.Inthismethodweleveragedstudentserviceclasswhichinturninteractedwiththedatabaseusingthedatabaseserviceclass.Finallywegottheresponsetextasasinglestring.Thisresponsetextisreturnedtotheclient.Uponreceivingtheresponse,thebrowserinvokedtheAjaxcallbackfunctionwhichinturnrefreshedtheregionusingdivtag.Withthisweachievedsettingastudentincontextbothontheserversideaswellastheclientside.

UseCase:Getstudentdetails.

RequirementsSpecificationReference:R5

PrototypeReference:P4

Prerequisite:Thestudenthastobeloadedintocontextfirst.

Thisusecaseneedstobeimplementedaspertherequirementsspecificationreferenceabove.TheUIneedstobeaspertheprototypereferenceabove.NowthatwehavecompleteclarityonusecaserequirementsandUIwewillnowproceedtoimplementthisusecase.

Inordertoimplementthisusecase,weneedtofollowthearchitectureandleveragetheframework.Toachievethiswewillfirstcomeupwithdetaileddesignandthencodeit.

Theprerequisiteforthisusecaseisthatastudentmustalreadybeexistinginthecontext,forthistheusermusthaveloadedthestudentthroughtheloadstudentusecase.Whenthestudentisloaded,thestudentidofaparticularstudentisaddedtothesession.Youcanrefertheloadstudentusecasefordetailsonthis.Letsassumeasofnowthatthestudentidisexistinginthehttpsession.Whentheuserclicksongetstudentdetailslinkeitherondashboardorviathemenu,thefollowingflowistriggered.

Theuserclicksthegetstudentdetailslink

ThehrefforthislinkisBisControllerServlet?ParameterActionCommand=GetStudentDetails

TheControllerServletisinvokedontheserver

IntheservicemethodtheactioncommandparametervalueisreadwhichisGetStudentDetails

TheexecutemethodforthecommandprocessorpertainingtoGetStudentDetailsisinvoked

Thebusinesslogicpertainingtothiscommandprocessorisexecutedandaviewisreturned

Theresponseisreturnedtothebrowserwiththisview

Theuserseesthestudentdetailspage

ThecommandprocessorclasspertainingtoGetStudentDetailscommandisGetStudentDetailsCP.TheviewpertainingtostudentdetailpageisStudentDetails.jsp.Now,letsseethesequenceofmethodcallsoncetheexecutemethodofGetStudentDetailsCPiscalled.Belowarethesequencediagramsfromthisusecase.

Asshownintheabovesequencediagrams,theGetStudentDetailsCPinvokestheprocessGetStudentDetailsmethodintheStudentDetailsServiceclass.Thismethodorchestratesthebusinesslogicforthisusecase.TheprivatemethodspopulateStudentnParentsInfoandpopulateBusInfowithintheStudentDetailsServiceclassareinvoked.Thesemethodsruntheappropriatequeryonthedatabaseandfetchthestudent,parentsandbusdetailsfromthedatabasetables.Inordertointeractwiththedatabase,theDatabaseServiceclassisleveraged.ThisdataisthenpopulatedtoabeancalledStudentDetailsBeanandthisbeanisthenaddedtothesession.Thecommandprocessoruponsuccessreturnstheviewasastring.Thisviewidentifiesthejsptoberesponded.Thejspreadsthisbeanfromthesessionandpresentsthisdatatotheuser.

Atthisstagewehavetherequirements,prototype,architecture,frameworkanddetaileddesignforthegetstudentdetailsusecaseintheformofsequenceandclassdiagrams.Thenextandthemostinterestingpartiscodingthisusecase.Intheearlierchapter,wehavealreadycreatedthedatabasetablesandaddedsometestdatathere.Letsidentifyalltheartifactsfirst.Forthisusecaseweneedthefollowingfiles.

BisHome.jsp

StudentDetails.jsp

BISScript.js

BISStyle.css

GetStudentDetailsCP.java

StudentDetailsService.java

StudentDetailsBean.java

DatabaseService.java

WewilllookintoBisHome.jsp,BISScript.js,BISStyle.cssandDatabaseService.javaundercommonssectionastheseartifactsarecommonforalltheusecases.Pleasereferchapter14fordetailsaboutthesesharedartifacts.

GetStudentDetailsCP.java

Pleasereferchapter14(TheBIS-SMSProjectComponents)forclassdiagramoncebeforeweproceedwiththisclass.ThisclassimplementsBisCommandinterfacewhichhasonly

onemethodexecute.ThisclassextendsBisCPwhichhasfewvariables.Wehavetoimplementexecutemethodinthisclassforgetstudentdetailsusecase.Letslookintotheactualsourcecodeforthisclassnow.

packagecom.bis.cp;

importcom.bis.session.StudentDetailsService;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importjavax.servlet.http.HttpSession;

importorg.apache.log4j.Logger;

publicclassGetStudentDetailsCPextendsBisCPimplementsBisCommand{

staticLoggerlogger=Logger.getLogger(GetStudentDetailsCP.class);

publicGetStudentDetailsCP(){

super();

}

publicStringexecute(HttpServletRequestrequest,HttpServletResponseresponse){

HttpSessionsession=request.getSession();

StringstrStudentId;

if(session!=null){

strStudentId=(String)session.getAttribute(“StudentId”);

if(strStudentId!=null){

StudentDetailsServicestudentDetailsService=newStudentDetailsService();try{

studentDetailsService.processGetStudentDetails(session);strNextNavigation=“StudentDetails”;

//Thenextnavigationpageuponsuccessfulprocessing.

}catch(Exceptione){

logger.error(e.getMessage());

strNextNavigation=“Error”;

//Thenextnavigationpageuponfailedprocessing.

}

}

else{

//strStudentIdisnull,firstentrytothepage.strNextNavigation=“StudentDetails”;

}

}

else{

//Sessionisnull.Validsessiondoesn’texist.RedirecttoLoginpage.strNextNavigation=“Login”;

}

returnstrNextNavigation;

}

}

TheexecutemethodofGetStudentDetailsCPClass.

Theexecutemethodiscalledfromthecontrollerservlet.Thisisthejoboftheframework.TheframeworkgetsthecommandfromUIandbasedonthecommandloadsandexecutesaspecificcommandprocessorexploitingthepolymorphicfeatureofjava.Inthiscase,thecommandfromUIis“GetStudentDetails”.Withintheservicemethodofcontrollerservlet,theGetStudentDetailsCPclassisloadedandinstantiatedandtheexecutemethodisinvoked.

Intheexecutemethod,thehttpsessionisfetchedfromtheHttpServletRequestobject.Fromthesession,thestudentidisfetched.Thisistheidofthestudentwhichisalreadyloadedintothecontext.TheexecutemethodfurtherinstantiatestheStudentDetailsServiceclassandinvokestheprocessGetStudentDetailsmethod.

StudentDetailsService.java

NowletsseetheStudentDetailsServiceclasssourcecode.

packagecom.bis.session;

importcom.bis.beans.StudentDetailsBean;

importcom.bis.db.DatabaseService;

importjava.sql.Connection;

importjava.sql.Date;

importjava.sql.ResultSet;

importjava.sql.SQLException;

importjava.sql.Statement;

importjava.text.SimpleDateFormat;

importjava.util.Hashtable;

importjava.util.StringTokenizer;

importjavax.servlet.http.HttpSession;

importorg.apache.log4j.Logger;

publicclassStudentDetailsServiceimplementsBisService{

staticLoggerlogger=Logger.getLogger(StudentDetailsService.class);

publicStudentDetailsService(){

super();

}

publicvoidprocessGetStudentDetails(HttpSessionsession){

StringstrStudentId=(String)session.getAttribute(“StudentId”);

StudentDetailsBeanstudentDetailsBean;

studentDetailsBean=newStudentDetailsBean();

if(strStudentId!=null){

//Thisismandatorybeforecallingthenextmethod.studentDetailsBean.setStudentId(strStudentId);

populateStudentnParentsInfo(studentDetailsBean);populateBusInfo(studentDetailsBean);

if(studentDetailsBean.getSiblings()!=null){populateSiblings(studentDetailsBean);

}

session.setAttribute(“studentDetailsBean”,studentDetailsBean);

}else{

logger.error(“Studentidisnull”);

}

}

privatevoidpopulateBusInfo(StudentDetailsBeanstudentDetailsBean){

StringstrBusId;

strBusId=studentDetailsBean.getBusId();

StringstrDriverFirstName;

StringstrDriverLastName;

StringstrDriverFullName;

StringstrHelperFirstName;

StringstrHelperLastName;

StringstrHelperFullName;

StringstrDesignation;

Connectionconnection=null;

Statementstatement=null;

ResultSetresultSet=null;

StringBuffersbQuery=newStringBuffer();

sbQuery.append(“SELECTED.DESIGNATION,ED.FIRST_NAME,ED.MIDDLE_NAME,ED.LAST_NAME,ED.MOBILE_NUMBER,TD.TRANSPORTATION_TYPE,TD.BUS_NUMBERFROMEMPLOYEE_DETAILSED,TRANSPORTATION_DETAILSTDWHERETD.BUS_ID=”);sbQuery.append(strBusId);

sbQuery.append(”AND(ED.EMPLOYEE_ID=TD.DRIVER_EMPLOYEE_IDORED.EMPLOYEE_ID=TD.HELPER_EMPLOYEE_ID)“);

if(strBusId!=null){

connection=DatabaseService.getDBConnection();

try{

statement=connection.createStatement();resultSet=statement.executeQuery(sbQuery.toString());

while(resultSet.next()){//Expectingtworecords.strDesignation=resultSet.getString(“DESIGNATION”);studentDetailsBean.setTransType(resultSet.getString(“TRANSPORTATION_TYPE”));studentDetailsBean.setBusNubmer(resultSet.getString(“BUS_NUMBER”));

if(strDesignation!=null){

if(strDesignation.equalsIgnoreCase(“Driver”)){strDriverFirstName=resultSet.getString(“FIRST_NAME”);

strDriverLastName=resultSet.getString(“LAST_NAME”);

strDriverFullName=strDriverFirstName+””+strDriverLastName;

studentDetailsBean.setDriver(strDriverFullName);

studentDetailsBean.setDriverMobile(resultSet.getString(“MOBILE_NUMBER”));

}

elseif(strDesignation.equalsIgnoreCase(“Helper”)){

strHelperFirstName=resultSet.getString(“FIRST_NAME”);

strHelperLastName=resultSet.getString(“LAST_NAME”);

strHelperFullName=strHelperFirstName+””+strHelperLastName;

studentDetailsBean.setHelper(strHelperFullName);studentDetailsBean.setHelperMobile(resultSet.getString(“MOBILE_NUMBER”));

}

else{

logger.debug(“Unknowndesignation.”);

}

}else{

logger.debug(“Designationisnull”);

}

}

}catch(SQLExceptionsqle){

logger.debug(sqle.getMessage());

}finally{

DatabaseService.closeDBResouces(statement,resultSet);

DatabaseService.releaseDBConnection();//Releasingdatabaseconnection.

}}else{

logger.debug(“Busidisnull”);

}}

privatevoidpopulateStudentnParentsInfo(StudentDetailsBeanstudentDetailsBean){

StringstrStudentId;

strStudentId=studentDetailsBean.getStudentId();

Connectionconnection=null;

Statementstatement=null;

ResultSetresultSet=null;

StringBuffersbQuery=newStringBuffer();

StringstrFirstName=””;

StringstrMiddleName=””;

StringstrLastName=””;

StringstrFullName=””;

StringstrTeacherFirstName=””;

StringstrTeacherMiddleName=””;

StringstrTeacherLastName=””;

StringstrTeacherFullName=””;

sbQuery.append(“SELECT\n”+

“studentDetails.FIRST_NAMEASSTUDENT_FIRST_NAME,studentDetails.MIDDLE_NAMEASSTUDENT_MIDDLE_NAME,studentDetails.LAST_NAMEASSTUDENT_LAST_NAME,\n”+

“studentDetails.GENDER_CODE,studentDetails.BIRTH_DATE,studentDetails.BLOOD_GROUP,studentDetails.BUS_ID,studentDetails.GRADE,studentDetails.SECTION,\n”+

“studentDetails.HEIGHT,studentDetails.WEIGHT,\n”+

“\n”+

“parentDetails.FATHER_NAME,parentDetails.MOTHER_NAME,parentDetails.FATHER_MOBILE,parentDetails.MOTHER_MOBILE,\n”+

“parentDetails.ADDRESS,\n”+

“\n”+

“employeeDetails.FIRST_NAMEASTEACHER_FIRST_NAME,employeeDetails.MIDDLE_NAMEASTEACHER_MIDDLE_NAME,employeeDetails.LAST_NAMEASTEACHER_LAST_NAME\n”+

“\n”+

“FROMSTUDENT_DETAILSstudentDetails,PARENT_DETAILSparentDetails,EMPLOYEE_DETAILSemployeeDetails,CLASS_TEACHER_MAPPINGCTM\n”+

“\n”+

“WHEREstudentDetails.STUDENT_ID=”);

sbQuery.append(”’”+strStudentId+”’“);

sbQuery.append(“ANDparentDetails.STUDENT_ID=studentDetails.STUDENT_IDANDCTM.GRADE=studentDetails.GRADEANDCTM.SECTION=studentDetails.SECTIONANDemployeeDetails.EMPLOYEE_ID=CTM.EMPLOYEE_ID”);

if(strStudentId!=null){

connection=DatabaseService.getDBConnection();

try{

statement=connection.createStatement();

resultSet=statement.executeQuery(sbQuery.toString());

resultSet.next();//Expectingonlyonerecord.

strFirstName=resultSet.getString(“STUDENT_FIRST_NAME”);

strMiddleName=resultSet.getString(“STUDENT_MIDDLE_NAME”);

strLastName=resultSet.getString(“STUDENT_LAST_NAME”);

if(strFirstName!=null){

strFullName=strFirstName;

}

if(strMiddleName!=null){

strFullName=strFullName+””+strMiddleName;

}

if(strLastName!=null){

strFullName=strFullName+””+strLastName;

}

studentDetailsBean.setFullName(strFullName);

strTeacherFirstName=resultSet.getString(“TEACHER_FIRST_NAME”);

strTeacherMiddleName=resultSet.getString(“TEACHER_MIDDLE_NAME”);

strTeacherLastName=resultSet.getString(“TEACHER_LAST_NAME”);

if(strTeacherFirstName!=null){

strTeacherFullName=strTeacherFirstName;

}

if(strTeacherMiddleName!=null){

strTeacherFullName=strTeacherFullName+””+strTeacherMiddleName;

}

if(strTeacherLastName!=null){

strTeacherFullName=strTeacherFullName+””+strTeacherLastName;

}

studentDetailsBean.setClassTeacher(strTeacherFullName);

StringstrGenderCode=resultSet.getString(“GENDER_CODE”);

if(strGenderCode!=null&&!(strGenderCode.trim()).equalsIgnoreCase(””)){

if(strGenderCode.equalsIgnoreCase(“F”)){

studentDetailsBean.setGender(“Female”);

}else{

studentDetailsBean.setGender(“Male”);

}

}

SimpleDateFormatsimpleDateFormat=newSimpleDateFormat(“dd-MMM-yyyy”);

DatebirthDate=resultSet.getDate(“BIRTH_DATE”);

if(birthDate!=null){studentDetailsBean.setDob(simpleDateFormat.format(birthDate));

}else{

logger.info(“DOBisnull”);

studentDetailsBean.setDob(“PleaseupdateDOB”);

}

StringstrBloodGroup=resultSet.getString(“BLOOD_GROUP”);

if(strBloodGroup!=null&&!(strBloodGroup.trim()).equalsIgnoreCase(””)){

if(strBloodGroup.equalsIgnoreCase(“AP”)){

studentDetailsBean.setBloodGroup(“A+ve”);

}elseif(strBloodGroup.equalsIgnoreCase(“AN”)){

studentDetailsBean.setBloodGroup(“A-ve”);

}elseif(strBloodGroup.equalsIgnoreCase(“BP”)){

studentDetailsBean.setBloodGroup(“B+ve”);

}elseif(strBloodGroup.equalsIgnoreCase(“BN”)){

studentDetailsBean.setBloodGroup(“B-ve”);

}elseif(strBloodGroup.equalsIgnoreCase(“OP”)){

studentDetailsBean.setBloodGroup(“O+ve”);

}elseif(strBloodGroup.equalsIgnoreCase(“ON”)){

studentDetailsBean.setBloodGroup(“O-ve”);

}elseif(strBloodGroup.equalsIgnoreCase(“ABP”)){

studentDetailsBean.setBloodGroup(“AB+ve”);

}elseif(strBloodGroup.equalsIgnoreCase(“ABN”)){

studentDetailsBean.setBloodGroup(“AB-ve”);

}

else{

//InvalidBloodGroup

studentDetailsBean.setBloodGroup(“PleaseupdateBloodGroup”);

logger.info(“InvalidBloodGroup”);

}

}else{

//Bloodgroupisnull

studentDetailsBean.setBloodGroup(“PleaseupdateBloodGroup”);

logger.info(“Bloodgroupisnull”);

}

studentDetailsBean.setFather(resultSet.getString(“FATHER_NAME”));studentDetailsBean.setFatherMobile(resultSet.getString(“FATHER_MOBILE”));studentDetailsBean.setMother(resultSet.getString(“MOTHER_NAME”));studentDetailsBean.setMotherMobile(resultSet.getString(“MOTHER_MOBILE”));studentDetailsBean.setAddress(resultSet.getString(“ADDRESS”));studentDetailsBean.setBusId(resultSet.getString(“BUS_ID”));studentDetailsBean.setGrade(resultSet.getString(“GRADE”));studentDetailsBean.setSection(resultSet.getString(“SECTION”));studentDetailsBean.setHeight(resultSet.getString(“HEIGHT”));studentDetailsBean.setWeight(resultSet.getInt(“WEIGHT”)+””);studentDetailsBean.setSiblings(resultSet.getString(“SIBLINGS_STUDENT_IDS”));

}catch(SQLExceptionsqle){

logger.error(sqle.getMessage());

}finally{

DatabaseService.closeDBResouces(statement,resultSet);

DatabaseService.releaseDBConnection();//Releasingdatabaseconnection.

}

}else{

logger.error(“Studentidisnull”);

}

}

publicStringloadStudent(StringstrStudentId){

StringstrStudentSummary=””;

StringstrFirstName=””;

StringstrMiddleName=””;

StringstrLastName=””;

StringstrFullName=””;

StringstrGrade=””;

StringstrSection=””;

Connectionconnection=null;

Statementstatement=null;

ResultSetresultSet=null;

if(strStudentId!=null){

StringBuffersbQuery=newStringBuffer(“SELECTFIRST_NAME,MIDDLE_NAME,LAST_NAME,GRADE,SECTIONFROMSTUDENT_DETAILSWHERESTUDENT_ID=’”);

sbQuery.append(strStudentId+”’”);

DatabaseServicedatabaseService=newDatabaseService();

connection=databaseService.getDBConnection();

try{

statement=connection.createStatement();

resultSet=statement.executeQuery(sbQuery.toString());

resultSet.next();//Expectingonlyonerecord.

strFirstName=resultSet.getString(“FIRST_NAME”);

strMiddleName=resultSet.getString(“MIDDLE_NAME”);

strLastName=resultSet.getString(“LAST_NAME”);

strGrade=resultSet.getString(“GRADE”);

strSection=resultSet.getString(“SECTION”);

if(strFirstName!=null){

strFullName=strFirstName;

}

if(strMiddleName!=null){

strFullName=strFullName+””+strMiddleName;

}

if(strLastName!=null){

strFullName=strFullName+””+strLastName;

}

strStudentSummary=strFullName+“&nbsp;&nbsp;|&nbsp;&nbsp;”+strGrade+“-”+strSection+“&nbsp;&nbsp;|&nbsp;&nbsp;”+strStudentId;

}catch(SQLExceptionsqle){

logger.error(sqle.getMessage());

}finally{

databaseService.closeDBResouces(statement,resultSet);

databaseService.releaseDBConnection();//Releasingdatabaseconnection.

}

}

else{

logger.error(“Studentidisnull”);

}

returnstrStudentSummary;

}

publicStringgetServiceName(){

returnthis.getClass().getName();

}}

TheprocessGetStudentDetailsmethodperformsthefollowingtasks:

Getsthestudentidfromthesession.

CreatesaninstanceofStudenDetailBeanandsetsthestudentid.

CallspopulateStudentnParentsInfoandpopulateBusInfomethodstopopulatethedatafromdatabaseintoStudenDetailBean.

AddsStudenDetailBeantothesessionwhichisconsumedbythejsp.

ThepopulateStudentnParentsInfomethodperformsthefollowingtasks:

Cooksupthedynamicselectqueryforagivenstudentid.

GetsthedatabaseconnectionfromDatabaseServiceclass.

Createsthestatementandexecutesthequery.

PopulatestheStudeneDetailsBeaninstancefromtheResultSetandaddsdatarelatedtostudentandparents.

ThepopulateBusInfomethodperformsthefollowingtasks:

Cooksupthedynamicselectqueryforagivenbusid.

GetsthedatabaseconnectionfromDatabaseServiceclass.

Createsthestatementandexecutesthequery.

PopulatestheStudeneDetailsBeaninstancefromtheResultSetandaddsdatarelatedtobusortransportation.

StudentDetailsBean.java

TheStudentDetailsBeanclassisjustasimplejavabeanwithprivatefieldswiththeirgettersandsetters.Pleaserefertheclassdiagramandbelowsourcecodeforunderstandingthisclass.

packagecom.bis.beans;

importjava.util.Hashtable;

publicclassStudentDetailsBeanextendsStudentBean{

publicStudentDetailsBean(){

super();

}

privatejava.lang.Stringgender;

privatejava.lang.Stringdob;

privatejava.lang.StringclassTeacher;

privatejava.lang.Stringheight;

privatejava.lang.Stringweight;

privatejava.lang.StringbloodGroup;

privatejava.lang.Stringsiblings;

privatejava.lang.StringbirthCity;

privatejava.lang.StringbirthStateCode;

privatejava.lang.StringbirthCountryCode;

privatejava.lang.Stringfather;

privatejava.lang.Stringmother;

privatejava.lang.StringfatherMobile;

privatejava.lang.StringmotherMobile;

privatejava.lang.Stringaddress;

privatejava.lang.StringbusId;

privatejava.lang.StringfatherQual;

privatejava.lang.StringmotherQual;

privatejava.lang.StringannualIncome;

privatejava.lang.Stringdriver;

privatejava.lang.StringdriverMobile;

privatejava.lang.Stringhelper;

privatejava.lang.StringhelperMobile;

privatejava.lang.StringbusNubmer;

privatejava.lang.StringtransType;

privatejava.util.HashtablesiblingsHash;

publicvoidsetGender(Stringgender){

this.gender=gender;

}

publicStringgetGender(){

returngender;

}

publicvoidsetDob(Stringdob){

this.dob=dob;

}

publicStringgetDob(){

returndob;

}

publicvoidsetClassTeacher(StringclassTeacher){

this.classTeacher=classTeacher;

}

publicStringgetClassTeacher(){

returnclassTeacher;

}

publicvoidsetHeight(Stringheight){

this.height=height;

}

publicStringgetHeight(){

returnheight;

}

publicvoidsetWeight(Stringweight){

this.weight=weight;

}

publicStringgetWeight(){

returnweight;

}

publicvoidsetBloodGroup(StringbloodGroup){

this.bloodGroup=bloodGroup;

}

publicStringgetBloodGroup(){

returnbloodGroup;

}

publicvoidsetSiblings(Stringsiblings){

this.siblings=siblings;

}

publicStringgetSiblings(){

returnsiblings;

}

publicvoidsetBirthCity(StringbirthCity){

this.birthCity=birthCity;

}

publicStringgetBirthCity(){

returnbirthCity;

}

publicvoidsetBirthStateCode(StringbirthStateCode){

this.birthStateCode=birthStateCode;

}

publicStringgetBirthStateCode(){

returnbirthStateCode;

}

publicvoidsetBirthCountryCode(StringbirthCountryCode){

this.birthCountryCode=birthCountryCode;

}

publicStringgetBirthCountryCode(){

returnbirthCountryCode;

}

publicvoidsetFather(Stringfather){

this.father=father;

}

publicStringgetFather(){

returnfather;

}

publicvoidsetMother(Stringmother){

this.mother=mother;

}

publicStringgetMother(){

returnmother;

}

publicvoidsetFatherMobile(StringfatherMobile){

this.fatherMobile=fatherMobile;

}

publicStringgetFatherMobile(){

returnfatherMobile;

}

publicvoidsetMotherMobile(StringmotherMobile){

this.motherMobile=motherMobile;

}

publicStringgetMotherMobile(){

returnmotherMobile;

}

publicvoidsetAddress(Stringaddress){

this.address=address;

}

publicStringgetAddress(){

returnaddress;

}

publicvoidsetBusId(StringbusId){

this.busId=busId;

}

publicStringgetBusId(){

returnbusId;

}

publicvoidsetFatherQual(StringfatherQual){

this.fatherQual=fatherQual;

}

publicStringgetFatherQual(){

returnfatherQual;}

publicvoidsetMotherQual(StringmotherQual){

this.motherQual=motherQual;

}

publicStringgetMotherQual(){

returnmotherQual;

}

publicvoidsetAnnualIncome(StringannualIncome){

this.annualIncome=annualIncome;

}

publicStringgetAnnualIncome(){

returnannualIncome;

}

publicvoidsetDriver(Stringdriver){

this.driver=driver;

}

publicStringgetDriver(){

returndriver;

}

publicvoidsetDriverMobile(StringdriverMobile){

this.driverMobile=driverMobile;

}

publicStringgetDriverMobile(){

returndriverMobile;

}

publicvoidsetHelper(Stringhelper){

this.helper=helper;

}

publicStringgetHelper(){

returnhelper;

}

publicvoidsetHelperMobile(StringhelperMobile){

this.helperMobile=helperMobile;

}

publicStringgetHelperMobile(){

returnhelperMobile;

}

publicvoidsetBusNubmer(StringbusNubmer){

this.busNubmer=busNubmer;

}

publicStringgetBusNubmer(){

returnbusNubmer;

}

publicvoidsetTransType(StringtransType){

this.transType=transType;

}

publicStringgetTransType(){

returntransType;

}

publicvoidsetSiblingsHash(HashtablesiblingsHash){

this.siblingsHash=siblingsHash;

}

publicHashtablegetSiblingsHash(){

returnsiblingsHash;

}

}

StudentDetails.jsp

ThisjspisdynamicallyincludedinBisHome.jspasaresultforgetstudentdetailsusecaseinvocationthroughuserinteractionwiththeUI..

TillnowwehaveseenthatthecommandforstudentdetailsgoesformUIasaresultofuserinteraction.Thenthecontrollerservletcallsgetstudentdetailscommandprocessorandthenthestudentdetailsserviceisleveraged.Finally,wegettheresultspackagedasaninstanceofStudentDetailsBean.Thisbeanisnowavailableinthesession.IntheStudentDetails.jspfilewefetchthisbeanfromthesession.Andfromthisbeanwefetchalltheinformationrelatedtostudentdetailsusingthegetters.Thestaticpartofthejspremainsthesameasthatoftheprototypepage.Onlythedynamicpartisaddedusingthebeanfromthesession.Hence,theenduserseestheviewforagivenstudentwithallhis/herdetails.

HereisthesourcecodefortheStudentDetails.jspfile.

<%@pageimport=“com.bis.beans.StudentDetailsBean”%>

<%@pageimport=“java.util.Hashtable,java.util.Enumeration”%>

<%

StudentDetailsBeanstudentDetailsBean=null;

if(session!=null){

studentDetailsBean=(StudentDetailsBean)session.getAttribute(“studentDetailsBean”);

}

%>

<formid=“frmStdDtls”name=“frmStdDtls”action=“BisControllerServlet”method=“POST”>

<inputtype=“hidden”name=“ParameterActionCommand”value=“GetStudentDetails”></input>

<tableborder=“0”cellpadding=“0”cellspacing=“0”width=“100%”height=“99%”>

<tr><td>&nbsp;</td></tr>

<tr><td>&nbsp;</td></tr>

<tr>

<tdbgcolor=“White”align=“center”colspan=“3”height=“30”>

<fontsize=“4”>

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getFullName());

}

%>

&nbsp;&nbsp;|&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getGrade());

out.print(”-“);

out.print(studentDetailsBean.getSection());

}

%>

&nbsp;&nbsp;|&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getStudentId());

}

%>

&nbsp;&nbsp;

</font>

</td>

</tr>

<tr><td>&nbsp;</td></tr>

<tr><td>&nbsp;</td></tr>

<tr><td>&nbsp;</td></tr>

<tr>

<tdwidht=”*”align=“center”valign=“top”>

<tableborder=“0”cellpadding=“10”cellspacing=“0”width=“100%”>

<trvalign=“top”>

<tdwidth=“33%”align=“center”>

<tableborder=“0”cellpadding=“3”cellspacing=“0”width=“90%”bgcolor=“White”>

<tr>

<tdcolspan=“2”align=“center”id=“trbgred”>

Student

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdwidth=“25%”align=“right”id=“clred”>StudentID&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getStudentId());

}

%>

</td>

</tr>

<tr>

<tdwidth=“25%”align=“right”id=“clred”>Name&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getFullName());

}

%>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdwidth=”*”align=“right”id=“clred”>Gender&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getGender());

}

%>

</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>Dateofbirth&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getDob());

}

%>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>Grade&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getGrade());

}

%>

</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>Section&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getSection());

}

%>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>ClassTeacher&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getClassTeacher());

}

%>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>Height&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getHeight());

}

%>

</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>Weight&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getWeight());

}

%>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>BloodGroup&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getBloodGroup());

}

%>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

</table>

</td>

<tdwidth=“33%”align=“center”>

<tableborder=“0”cellpadding=“3”cellspacing=“0”width=“90%”bgcolor=“White”>

<tr>

<tdcolspan=“2”align=“center”id=“trbgred”>

Parents

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdwidth=“25%”align=“right”id=“clred”>Father&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getFather());

}

%>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdwidth=“25%”align=“right”id=“clred”>Mobile&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getFatherMobile());

}

%>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdwidth=”*”align=“right”id=“clred”>Mother&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getMother());

}

%>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>Mobile&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getMotherMobile());

}

%>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<trheight=“75”>

<tdalign=“right”id=“clred”>Address&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getAddress());

}

%>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

</table>

</td>

<tdwidth=”*”align=“center”>

<tableborder=“0”cellpadding=“3”cellspacing=“0”width=“90%”bgcolor=“White”>

<tr>

<tdcolspan=“2”align=“center”id=“trbgred”>

Bus

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdwidth=“25%”align=“right”id=“clred”>BusId&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getBusId());

}

%>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdwidth=“25%”align=“right”id=“clred”>Driver&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getDriver());

}

%>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdwidth=”*”align=“right”id=“clred”>Mobile&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getDriverMobile());

}

%>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>Helper&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getHelper());

}

%>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>Mobile&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getHelperMobile());

}

%>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>BusNumber&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getBusNubmer());

}

%>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>Transportation&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

&nbsp;&nbsp;

<%

if(studentDetailsBean!=null){

out.print(studentDetailsBean.getTransType());

}

%>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

</table>

</td>

</tr>

</table>

</td>

</tr>

<tr><td>&nbsp;</td></tr>

</table>

</form>

Thisconcludesthegetstudentdetailsusecaseimplementationfromendtoend.Wecomposedtherequirementspecifications,webuilttheprototype,wefollowedthearchitectureforthesolution,weleveragedtheframework,wedevelopedthevariousjavaclasses,weusedthecommoncomponentslikeDatabaseService.java,BISStyle.cssetcandwebuilttheviewwiththejsppage.

UseCase:Getstudentattendance.

RequirementsSpecificationReference:R7

PrototypeReference:P6

Prerequisite:Thestudenthastobeloadedintocontextfirst.

Thisusecaseneedstobeimplementedaspertherequirementsspecificationreferenceabove.TheUIneedstobeaspertheprototypereferenceabove.NowthatwehavecompleteclarityonusecaserequirementsandUIwewillnowproceedtoimplementthisusecase.

Inordertoimplementthisusecase,weneedtofollowthearchitectureandleveragetheframework.Toachievethiswewillfirstcomeupwithdetaileddesignandthencodeit.

Theprerequisiteforthisusecaseisthatastudentmustalreadybeexistinginthecontext,forthistheusermusthaveloadedthestudentthroughtheloadstudentusecase.Whenthestudentisloaded,thestudentidofaparticularstudentisaddedtothesession.Youcanrefertheloadstudentusecasefordetailsonthis.Letsassumeasofnowthatthestudentidisexistinginthehttpsession.Whentheuserclicksongetstudentattendance(eitherforsemesterIorforsemesterII)linkeitherondashboardorviathemenu,thefollowingflowistriggered.

Getstudentattendancelinkisclicked

Thehreffortheselinksare

BisControllerServlet?ParameterActionCommand=GetStudentAttendance&sem=1and

BisControllerServlet?ParameterActionCommand=GetStudentAttendance&sem=2

TheControllerServletisinvokedontheserver

IntheservicemethodtheactioncommandparametervalueisreadwhichisGetStudentAttendance

TheexecutemethodforthecommandprocessorpertainingtoGetStudentAttendanceisinvoked

Thebusinesslogicpertainingtothiscommandprocessorisexecutedandaviewisreturned

Theresponseisreturnedtothebrowserwiththisview

Theuserseesthestudentattendancepageforagivensemester

ThecommandprocessorclasspertainingtoGetStudentAttendancecommandisGetStudentAttendanceCP.TheviewpertainingtostudentdetailpageisStudentAttendance.jsp.ReferthecodebelowtoseethesequenceofmethodcallsoncetheexecutemethodofGetStudentAttendanceCPisinvoked.

Forthisusecaseweneedthefollowingfiles.

1.GetStudentAttendanceCP.java

2.StudentAttendanceService.java

3.StudentAttendanceBean.java

4.StudentAttendance.jsp

GetStudentAttendanceCP.java

packagecom.bis.cp;

importcom.bis.session.StudentAttendanceService;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importjavax.servlet.http.HttpSession;

importorg.apache.log4j.Logger;

publicclassGetStudentAttendanceCPextendsBisCPimplementsBisCommand{

staticLoggerlogger=Logger.getLogger(GetStudentAttendanceCP.class);

publicGetStudentAttendanceCP(){

super();

}

publicStringexecute(HttpServletRequestrequest,HttpServletResponseresponse){

HttpSessionsession=request.getSession();

StringstrStudentId;

StringstrSemester=“1”;//Defaultingsemestertofirst.

strSemester=request.getParameter(“sem”);

if(session!=null){

strStudentId=(String)session.getAttribute(“StudentId”);

if(strStudentId!=null&&!(strStudentId.trim().equalsIgnoreCase(””))){

StudentAttendanceServicestudentAttendanceService=newStudentAttendanceService();

try{

studentAttendanceService.processGetStudentAttendance(session,strSemester);

strNextNavigation=“StudentAttendance”;//Thenextnavigationpageuponsuccessfulprocessing.

}catch(Exceptione){

logger.error(e.getMessage());

strNextNavigation=“Error”;//Thenextnavigationpageuponfailedprocessing.

}

}

else{

//strStudentIdisnull,firstentrytothepage.

strNextNavigation=“StudentAttendance”;

}

}

else{

//sessionisnull.Validsessiondoesnotexists.RedirecttoLoginpage.

strNextNavigation=“Login”;

}

returnstrNextNavigation;

}

}

Theexecutemethodperformsthefollowingactions:

GetstheHttpsessionfortheloggedinuser.

Getsthesemestertheuserhasselectedasaparametervalue.

Getsthestudentidfromthesession.

CreatesaninstanceofStudentAttendanceServiceandinvokesprocessGetStudentAttendancemethod.

SetsthenextnavigationtoStudentAttendance.

StudentAttendanceService.java

packagecom.bis.session;

importcom.bis.beans.StudentAttendanceBean;

importcom.bis.db.DatabaseService;

importjava.sql.Connection;

importjava.sql.PreparedStatement;

importjava.sql.ResultSet;

importjava.sql.SQLException;

importjava.sql.Statement;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpSession;

importorg.apache.log4j.Logger;

publicclassStudentAttendanceServiceimplementsBisService{

staticLoggerlogger=Logger.getLogger(StudentAttendanceService.class);

publicStudentAttendanceService(){

super();

}

publicvoidprocessGetStudentAttendance(HttpSessionsession,StringstrSemester){

StringstrStudentId=(String)session.getAttribute(“StudentId”);

StudentAttendanceBeanstudentAttendanceBean;

studentAttendanceBean=newStudentAttendanceBean();

if(strStudentId!=null){

studentAttendanceBean.setStudentId(strStudentId);//Thisismandatorybeforecallingthenextmethod.

populateStudentAttendance(studentAttendanceBean,strSemester);

populateWorkingDaysforSem(studentAttendanceBean,strSemester);

session.setAttribute(“studentAttendanceBean”,studentAttendanceBean);

}else{

logger.error(“StudentIdisnull”);

}

}

privatevoidpopulateStudentAttendance(StudentAttendanceBeanstudentAttendanceBean,StringstrSemester){

StringstrStudentId;

strStudentId=studentAttendanceBean.getStudentId();

Connectionconnection=null;

Statementstatement=null;

ResultSetresultSet=null;

StringBuffersbQuery=newStringBuffer();

sbQuery.append(“SELECTATTENDANCEFROMSTUDENT_ATTENDANCEWHERESTUDENT_ID=”);

sbQuery.append(”’”+strStudentId+”’“);

sbQuery.append(“ANDSEMESTER=’”);

sbQuery.append(strSemester);

sbQuery.append(”’”);

if(strStudentId!=null){

connection=DatabaseService.getDBConnection();

try{

statement=connection.createStatement();

resultSet=statement.executeQuery(sbQuery.toString());

resultSet.next();//Expectingonlyonerecord.

studentAttendanceBean.setAttendance(resultSet.getInt(“ATTENDANCE”));

}catch(SQLExceptionsqle){

logger.error(sqle.getMessage());

}finally{

DatabaseService.closeDBResouces(statement,resultSet);

DatabaseService.releaseDBConnection();//Releasingdatabaseconnection.

}

}else{

logger.error(“Studentidisnull”);

}

}

privatevoidpopulateWorkingDaysforSem(StudentAttendanceBeanstudentAttendanceBean,StringstrSemester){

Connectionconnection=null;

Statementstatement=null;

ResultSetresultSet=null;

StringBuffersbQuery=newStringBuffer();

sbQuery.append(“SELECTVALUEFROMBIS_CONSTANTSWHEREPROPERTY=’”);

if(strSemester.equalsIgnoreCase(“1”)){

sbQuery.append(“SEM_ONE_WORKING_DAYS’”);

}elseif(strSemester.equalsIgnoreCase(“2”)){

sbQuery.append(“SEM_TWO_WORKING_DAYS’”);

}else{

logger.debug(“Invalidsemesterreturned”);

}

DatabaseServicedatabaseService=newDatabaseService();

connection=databaseService.getDBConnection();

try{

statement=connection.createStatement();

resultSet=statement.executeQuery(sbQuery.toString());

resultSet.next();//Expectingonlyonerecord.

studentAttendanceBean.setTotalWorkingDays(Integer.parseInt(resultSet.getString(“VALUE”)));

}catch(SQLExceptionsqle){

logger.error(sqle.getMessage());

}finally{

databaseService.closeDBResouces(statement,resultSet);

databaseService.releaseDBConnection();//Releasingdatabaseconnection.

}

}

//GetsstudentattendanceforManageattendancepage.Thisincludesattendanceforboththesemesters.

publicvoidprocessGetStudentAttendance(HttpSessionsession)throwsException{

StringstrStudentId=(String)session.getAttribute(“StudentId”);

StudentAttendanceBeanstudentAttendanceBean;

studentAttendanceBean=newStudentAttendanceBean();

if(strStudentId!=null){

studentAttendanceBean.setStudentId(strStudentId);//Thisismandatorybeforecallingthenextmethod.

populateStudentAttendance(studentAttendanceBean);

populateWorkingDaysforBothSem(studentAttendanceBean);

session.setAttribute(“studentAttendanceBean”,studentAttendanceBean);

}else{

logger.error(“Studentidisnull”);

}

}

//Populatesattendanceforboththesemestersforagivenstudent.

privatevoidpopulateStudentAttendance(StudentAttendanceBeanstudentAttendanceBean){

StringstrStudentId;

StringstrSem;

strStudentId=studentAttendanceBean.getStudentId();

Connectionconnection=null;

Statementstatement=null;

ResultSetresultSet=null;

StringBuffersbQuery=newStringBuffer();

sbQuery.append(“SELECTATTENDANCE,SEMESTERFROMSTUDENT_ATTENDANCEWHERESTUDENT_ID=”);

sbQuery.append(”’”+strStudentId+”’“);

if(strStudentId!=null){

DatabaseServicedatabaseService=newDatabaseService();

connection=databaseService.getDBConnection();

try{

statement=connection.createStatement();

resultSet=statement.executeQuery(sbQuery.toString());

//Expectingtworecords.Oneforeachsemester.

while(resultSet.next()){

strSem=resultSet.getString(“SEMESTER”);

if(strSem!=null){

if(strSem.equalsIgnoreCase(“1”)){

studentAttendanceBean.setSemOneAttendance(resultSet.getInt(“ATTENDANCE”));

}elseif(strSem.equalsIgnoreCase(“2”)){

studentAttendanceBean.setSemTwoAttendance(resultSet.getInt(“ATTENDANCE”));

}

}

}

}catch(SQLExceptionsqle){

logger.error(sqle.getMessage());

}finally{

databaseService.closeDBResouces(statement,resultSet);

databaseService.releaseDBConnection();//Releasingdatabaseconnection.

}

}else{

logger.error(“Studentidisnull”);

}

}

privatevoidpopulateWorkingDaysforBothSem(StudentAttendanceBeanstudentAttendanceBean){

StringstrSem;

Connectionconnection=null;

Statementstatement=null;

ResultSetresultSet=null;

StringBuffersbQuery=

newStringBuffer(“SELECTPROPERTY,VALUEFROMBIS_CONSTANTSWHEREPROPERTY=‘SEM_ONE_WORKING_DAYS’ORPROPERTY=‘SEM_TWO_WORKING_DAYS’”);

DatabaseServicedatabaseService=newDatabaseService();

connection=databaseService.getDBConnection();

try{

statement=connection.createStatement();

resultSet=statement.executeQuery(sbQuery.toString());

//Expectingtworecords.Oneforeachsemester.

while(resultSet.next()){

strSem=resultSet.getString(“PROPERTY”);

if(strSem!=null){

if(strSem.equalsIgnoreCase(“SEM_ONE_WORKING_DAYS”)){

studentAttendanceBean.setSemOneTotalWorkingDays(Integer.parseInt(resultSet.getString(“VALUE”)));

}elseif(strSem.equalsIgnoreCase(“SEM_TWO_WORKING_DAYS”)){

studentAttendanceBean.setSemTwoTotalWorkingDays(Integer.parseInt(resultSet.getString(“VALUE”)));

}

}

}

}catch(SQLExceptionsqle){

logger.error(sqle.getMessage());

}finally{

databaseService.closeDBResouces(statement,resultSet);

databaseService.releaseDBConnection();//Releasingdatabaseconnection.

}

}

//Updatesthestudent’sattendanceforthegivensemesterindatabase.

publicvoidupdateStudentAttendance(HttpServletRequestrequest){

StringstrAttendance=null,strUpdateQuery=null,strSem=null,strStudentId=null;

intupdateCount;

Connectionconnection=null;

PreparedStatementpreparedStatement=null;

DatabaseServicedatabaseService=newDatabaseService();

connection=databaseService.getDBConnection();

strUpdateQuery=“UPDATESTUDENT_ATTENDANCESETATTENDANCE=?WHERESTUDENT_ID=?ANDSEMESTER=?”;

strStudentId=(String)request.getSession().getAttribute(“StudentId”);

strSem=request.getParameter(“ParameterUpdateSemAttendance”);

if(strSem!=null){

if(strSem.equalsIgnoreCase(“1”)){

strAttendance=request.getParameter(“txtPresentSemOne”);

}elseif(strSem.equalsIgnoreCase(“2”)){

strAttendance=request.getParameter(“txtPresentSemTwo”);

}

}

else{

logger.debug(“Semesterisnull”);

}

if(strAttendance!=null&&strStudentId!=null){

logger.info(“strAttendance:“+strAttendance);

logger.info(“strStudentId:“+strStudentId);

try{

preparedStatement=connection.prepareStatement(strUpdateQuery);

preparedStatement.setInt(1,Integer.parseInt(strAttendance));

preparedStatement.setString(2,strStudentId);

preparedStatement.setString(3,strSem);

updateCount=preparedStatement.executeUpdate();

logger.info(“Theudatecountforattendancupdateis:“+updateCount);

}catch(SQLExceptionsqle){

logger.error(sqle.getMessage());

}catch(NumberFormatExceptionnfe){

logger.error(nfe.getMessage());

}finally{

databaseService.closeDBResouces(preparedStatement,null);

databaseService.releaseDBConnection();//Releasingdatabaseconnection.

}

}else{

logger.error(“Attendanceorstudentidisnull”);

}

}

publicStringgetServiceName(){

returnthis.getClass().getName();

}

}

TheprocessGetStudentAttendancemethodperformsthefollowingtasks:

Getsthestudentidfromthesession.

CreatesaninstanceofStudentAttendanceBean.

CallssetterofStudentAttendanceBeaninstanceforsettingstudentid.

InvokestheprivatemethodspopulateStudentAttendanceandpopulateWorkingDaysforSem.

AddsthepopulatedStudentAttendanceBeaninstancetosessiontobeconsumedbytheview.

ThepopulateStudentAttendancemethodperformsthefollowingtasks:

Cooksupadynamicqueryforagivenstudentandsemestertofetchtheattendancefromthedatabase.

LeveragestheDatabaseServiceclasstogetthedatabaseconnection.

CallssetterofStudentAttendanceBeaninstanceforsettingtheattendance.

Usesthefinallyblocktoclosealltheresourcesrelatedtodatabase.

ThepopulateWorkingDaysforSemmethodperformsthefollowingtasks:

QueriesBIS_CONSTANTStableforthepropertybasedonsemesterrequestedbytheuser.SEM_ONE_WORKING_DAYSforsemesteroneandSEM_TWO_WORKING_DAYSforsemestertwo.

LeveragestheDatabaseServiceclasstogetthedatabaseconnection.

CallssetterofStudentAttendanceBeaninstanceforsettingthetotalnumberofworkingdaysforthegivensemester.

Usesthefinallyblocktoclosealltheresourcesrelatedtodatabase.

StudentAttendanceBean.java

TheStudentAttendanceBeanclassisjustasimplejavabeanwithprivatefieldswiththeirgettersandsetters.Pleaserefertheclassdiagramandbelowsourcecodeforunderstandingthisclass.

packagecom.bis.beans;

publicclassStudentAttendanceBeanextendsStudentBean{

publicStudentAttendanceBean(){

super();

}

privateintattendance;

privateinttotalWorkingDays;

privateintsemOneAttendance;

privateintsemTwoAttendance;

privateintsemOneTotalWorkingDays;

privateintsemTwoTotalWorkingDays;

publicvoidsetAttendance(intattendance){

this.attendance=attendance;

}

publicintgetAttendance(){

returnattendance;

}

publicvoidsetTotalWorkingDays(inttotalWorkingDays){

this.totalWorkingDays=totalWorkingDays;

}

publicintgetTotalWorkingDays(){

returntotalWorkingDays;

}

publicvoidsetSemOneAttendance(intsemOneAttendance){

this.semOneAttendance=semOneAttendance;

}

publicintgetSemOneAttendance(){

returnsemOneAttendance;

}

publicvoidsetSemTwoAttendance(intsemTwoAttendance){

this.semTwoAttendance=semTwoAttendance;

}

publicintgetSemTwoAttendance(){

returnsemTwoAttendance;

}

publicvoidsetSemOneTotalWorkingDays(intsemOneTotalWorkingDays){

this.semOneTotalWorkingDays=semOneTotalWorkingDays;

}

publicintgetSemOneTotalWorkingDays(){

returnsemOneTotalWorkingDays;

}

publicvoidsetSemTwoTotalWorkingDays(intsemTwoTotalWorkingDays){

this.semTwoTotalWorkingDays=semTwoTotalWorkingDays;

}

publicintgetSemTwoTotalWorkingDays(){

returnsemTwoTotalWorkingDays;

}

}

StudentAttendance.jsp

ThisjspisdynamicallyincludedinBisHome.jspasaresultforgetstudentattendanceusecaseinvocationthroughuserinteractionwiththeUI.

TillnowwehaveseenthatthecommandforstudentattendancegoesformUIasaresultofuserinteraction.Thenthecontrollerservletcallsgetstudentattendancecommandprocessorandthenthestudentattendanceserviceisleveraged.Finally,wegettheresultspackagedasaninstanceofStudentAttendanceBean.Thisbeanisnowavailableinthesession.IntheStudentAttendance.jspfilewefetchthisbeanfromthesession.Andfromthisbeanwefetchalltheinformationrelatedtostudentattendanceusingthegetters.Thestaticpartofthejspremainsthesameasthatoftheprototypepage.Onlythedynamicpartisaddedusingthebeanfromthesession.Hence,theenduserseestheviewforagivenstudentandsemesterwithalltheattendancerelateddetails.

HereisthesourcecodefortheStudentAttendance.jspfile.

<%@pageimport=“com.bis.beans.StudentResultsBean,com.bis.beans.StudentAttendanceBean”%>

<%@pageimport=“java.util.Hashtable,java.util.Enumeration”%>

<%

StudentResultsBeanstudentResultsBean=null;

intinPresentPercentage=0;

intinTotal=0;

intinPresent=0;

StudentAttendanceBeanstudentAttendanceBean=null;

if(session!=null){

studentResultsBean=(StudentResultsBean)session.getAttribute(“studentResultsBean”);

studentAttendanceBean=(StudentAttendanceBean)session.getAttribute(“studentAttendanceBean”);

}

if(studentAttendanceBean!=null){

inTotal=studentAttendanceBean.getTotalWorkingDays();

inPresent=studentAttendanceBean.getAttendance();

if(inTotal>0&&inPresent>0){

inPresentPercentage=Math.abs(100*inPresent/inTotal);

}

}

%>

<formid=“frmStudentAttendance”>

<tableborder=“0”cellpadding=“10”cellspacing=“0”width=“100%”>

<tr><td>&nbsp;</td></tr>

<tr>

<tdbgcolor=“White”align=“center”colspan=“3”>

<fontsize=“4”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getFullName());

}

%>

&nbsp;&nbsp;|&nbsp;&nbsp;

<%

StringstrSem=request.getParameter(“sem”);

if(strSem!=null){

if(strSem.equalsIgnoreCase(“1”)){

strSem=“Semester-I”;

}

else{

strSem=“Semester-II”;

}

}

else{

strSem=“Semester-I”;

}

out.print(strSem);

%>

&nbsp;&nbsp;|&nbsp;&nbsp;

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getGrade());

out.print(”-“);

out.print(studentResultsBean.getSection());

}

%>

&nbsp;&nbsp;|&nbsp;&nbsp;

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getStudentId());

}

%>

&nbsp;&nbsp;

</font>

</td>

</tr>

<tr><td>&nbsp;</td></tr>

<tralign=“center”>

<tdheight=“250px”>

<tableborder=“1”cellpadding=“5”cellspacing=“0”width=“70%”>

<trvalign=“middle”bgcolor=“White”>

<tdbgcolor=“White”align=“center”height=“100px”width=“100%”colspan=“2”>

Total-

<%

if(studentAttendanceBean!=null){

out.print(studentAttendanceBean.getTotalWorkingDays());

}

%>

Days.

</td>

</tr>

<trvalign=“middle”bgcolor=“White”id=“bigwhtxt”>

<tdbgcolor=“Green”align=“center”height=“200px”width=”<%=inPresentPercentage%>%”>

Present-<%=inPresentPercentage%>%

</td>

<tdbgcolor=“Red”align=“center”height=“200px”width=”*”>Absent-<%=(100-inPresentPercentage)%>%</td>

</tr>

<trvalign=“middle”bgcolor=“White”>

<tdbgcolor=“White”align=“center”height=“100px”width=“100%”colspan=“2”>

|&nbsp;&nbsp;&nbsp;

Present-

<%

if(studentAttendanceBean!=null){

out.print(studentAttendanceBean.getAttendance());

}

%>

&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;

Absent-

<%

if(studentAttendanceBean!=null){

intintAbsent=studentAttendanceBean.getTotalWorkingDays()-studentAttendanceBean.getAttendance();

out.print(intAbsent);

}

%>

&nbsp;&nbsp;&nbsp;|

</td>

</tr>

</table>

</td>

</tr>

<tr><td>&nbsp;</td></tr>

</table>

</form>

Thisconcludesthegetattendancedetailsusecaseimplementationfromendtoend.Wecomposedtherequirementspecifications,webuilttheprototype,wefollowedthearchitectureforthesolution,weleveragedtheframework,wedevelopedthevariousjavaclasses,weusedthecommoncomponentslikeDatabaseService.java,BISStyle.cssetcandwebuilttheviewwiththejsppage.

UseCase:Getstudentfees.

RequirementsSpecificationReference:R8

PrototypeReference:P7

Prerequisite:Thestudenthastobeloadedintocontextfirst.

Thisusecaseneedstobeimplementedaspertherequirementsspecificationreferenceabove.TheUIneedstobeaspertheprototypereferenceabove.NowthatwehavecompleteclarityonusecaserequirementsandUIwewillnowproceedtoimplementthisusecase.

Inordertoimplementthisusecase,weneedtofollowthearchitectureandleveragetheframework.Toachievethiswewillfirstcomeupwithdetaileddesignandthencodeit.

Theprerequisiteforthisusecaseisthatastudentmustalreadybeexistinginthecontext,forthistheusermusthaveloadedthestudentthroughtheloadstudentusecase.Whenthestudentisloaded,thestudentidofaparticularstudentisaddedtothesession.Youcanrefertheloadstudentusecasefordetailsonthis.Letsassumeasofnowthatthestudentidisexistinginthehttpsession.Whentheuserclicksthestudentfeeslinkeitherondashboardorviathemenu,thefollowingflowistriggered.

Getstudentfeeslinkisclicked

Thehrefforthelinkis

BisControllerServlet?ParameterActionCommand=GetStudentFees

TheControllerServletisinvokedontheserver

IntheservicemethodtheactioncommandparametervalueisreadwhichisGetStudentFees

TheexecutemethodforthecommandprocessorpertainingtoGetStudentFeesisinvoked

Thebusinesslogicpertainingtothiscommandprocessorisexecutedandaviewisreturned

Theresponseisreturnedtothebrowserwiththisview

Theuserseesthestudentfeespage

ThecommandprocessorclasspertainingtoGetStudentFeescommandisGetStudentFeesCP.TheviewpertainingtostudentdetailpageisStudentFees.jsp.ReferthecodebelowtoseethesequenceofmethodcallsoncetheexecutemethodofGetStudentFeesCPiscalled.

Forthisusecaseweneedthefollowingfiles.

1.GetStudentFeesCP.java

2.StudentFeesService.java

3.StudentFeesBean.java

4.StudentFees.jsp

GetStudentFeesCP.java

packagecom.bis.cp;

importcom.bis.session.StudentFeesService;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importjavax.servlet.http.HttpSession;

importorg.apache.log4j.Logger;

publicclassGetStudentFeesCPextendsBisCPimplementsBisCommand{

staticLoggerlogger=Logger.getLogger(GetStudentFeesCP.class);

publicGetStudentFeesCP(){

super();

}

publicStringexecute(HttpServletRequestrequest,HttpServletResponseresponse){

HttpSessionsession=request.getSession();

StringstrStudentId;

if(session!=null){

strStudentId=(String)session.getAttribute(“StudentId”);

if(strStudentId!=null&&!(strStudentId.trim().equalsIgnoreCase(””))){

StudentFeesServicestudentFeesService=newStudentFeesService();

try{

studentFeesService.processGetFeesDetails(session);

strNextNavigation=“StudentFees”;//Thenextnavigationpageuponsuccessfulprocessing.

}catch(Exceptione){

logger.error(e.getMessage());

strNextNavigation=“Error”;//Thenextnavigationpageuponfailedprocessing.

}

}

else{

//strStudentIdisnull,firstentrytothepage.

strNextNavigation=“StudentFees”;

}

}

else{

//sessionisnull.Validsessiondoesn’texsit.RedirecttoLoginpage.

strNextNavigation=“Login”;

}

returnstrNextNavigation;

}

}

Theexecutemethodperformsthefollowingactions:

GetstheHttpsessionfortheloggedinuser.

Getsthestudentidfromthesession.

CreatesaninstanceofStudentFeesServiceandinvokesprocessGetFeesDetailsmethod.

SetsthenextnavigationtoStudentFees.

StudentFeesService.java

packagecom.bis.session;

importcom.bis.beans.StudentFeesBean;

importcom.bis.db.DatabaseService;

importjava.sql.Connection;

importjava.sql.ResultSet;

importjava.sql.SQLException;

importjava.sql.Statement;

importjavax.servlet.http.HttpSession;

importorg.apache.log4j.Logger;

publicclassStudentFeesServiceimplementsBisService{

staticLoggerlogger=Logger.getLogger(StudentFeesService.class);

publicStudentFeesService(){

super();

}

publicvoidprocessGetFeesDetails(HttpSessionsession){

StringstrStudentId=(String)session.getAttribute(“StudentId”);

StudentFeesBeanstudentFeesBean;

studentFeesBean=newStudentFeesBean();

if(strStudentId!=null){

studentFeesBean.setStudentId(strStudentId);//Thisismandatorybeforecallingthenextmethod.

populateFeesInfo(studentFeesBean);

session.setAttribute(“studentFeesBean”,studentFeesBean);

}else{

logger.error(“Studentidisnull”);

}

}

privatevoidpopulateFeesInfo(StudentFeesBeanstudentFeesBean){

StringstrStudentId;

strStudentId=studentFeesBean.getStudentId();

Connectionconnection=null;

Statementstatement=null;

ResultSetresultSet=null;

StringBuffersbQuery=newStringBuffer();

sbQuery.append(“SELECTJAN_ACAD,FEB_ACAD,MAR_ACAD,APR_ACAD,MAY_ACAD,JUN_ACAD,\n”+

“JUL_ACAD,AUG_ACAD,SEP_ACAD,OCT_ACAD,NOV_ACAD,DEC_ACAD,\n”+

“JAN_BUS,FEB_BUS,MAR_BUS,APR_BUS,MAY_BUS,JUN_BUS,\n”+

“JUL_BUS,AUG_BUS,SEP_BUS,OCT_BUS,NOV_BUS,DEC_BUS\n”+

“FROMSTUDENT_FEES\n”+

“WHERESTUDENT_ID=”);

sbQuery.append(”’”+strStudentId+”’”);

if(strStudentId!=null){

connection=DatabaseService.getDBConnection();

try{

statement=connection.createStatement();

resultSet=statement.executeQuery(sbQuery.toString());

resultSet.next();//Expectingonlyonerecord.

studentFeesBean.setJanAcad(resultSet.getString(“JAN_ACAD”));

studentFeesBean.setFebAcad(resultSet.getString(“FEB_ACAD”));

studentFeesBean.setMarAcad(resultSet.getString(“MAR_ACAD”));

studentFeesBean.setAprAcad(resultSet.getString(“APR_ACAD”));

studentFeesBean.setMayAcad(resultSet.getString(“MAY_ACAD”));

studentFeesBean.setJunAcad(resultSet.getString(“JUN_ACAD”));

studentFeesBean.setJulAcad(resultSet.getString(“JUL_ACAD”));

studentFeesBean.setAugAcad(resultSet.getString(“AUG_ACAD”));

studentFeesBean.setSepAcad(resultSet.getString(“SEP_ACAD”));

studentFeesBean.setOctAcad(resultSet.getString(“OCT_ACAD”));

studentFeesBean.setNovAcad(resultSet.getString(“NOV_ACAD”));

studentFeesBean.setDecAcad(resultSet.getString(“DEC_ACAD”));

studentFeesBean.setJanBus(resultSet.getString(“JAN_BUS”));

studentFeesBean.setFebBus(resultSet.getString(“FEB_BUS”));

studentFeesBean.setMarBus(resultSet.getString(“MAR_BUS”));

studentFeesBean.setAprBus(resultSet.getString(“APR_BUS”));

studentFeesBean.setMayBus(resultSet.getString(“MAY_BUS”));

studentFeesBean.setJunBus(resultSet.getString(“JUN_BUS”));

studentFeesBean.setJulBus(resultSet.getString(“JUL_BUS”));

studentFeesBean.setAugBus(resultSet.getString(“AUG_BUS”));

studentFeesBean.setSepBus(resultSet.getString(“SEP_BUS”));

studentFeesBean.setOctBus(resultSet.getString(“OCT_BUS”));

studentFeesBean.setNovBus(resultSet.getString(“NOV_BUS”));

studentFeesBean.setDecBus(resultSet.getString(“DEC_BUS”));

}catch(SQLExceptionsqle){

logger.error(sqle.getMessage());

}

finally{

DatabaseService.closeDBResouces(statement,resultSet);

DatabaseService.releaseDBConnection();//Releasingdatabaseconnection.

}

}else{

logger.error(“Studentidisnull”);

}

}

publicStringgetServiceName(){

returnthis.getClass().getName();

}

}

TheprocessGetFeesDetailsmethodperformsthefollowingtasks:

Getsthestudentidfromthesession.

CreatesaninstanceofStudenFeesBeanandsetsthestudentid.

CallspopulateFeesInfomethodtopopulatethedatafromdatabaseintoStudenFeesBean.

AddsStudenFeesBeantothesessionwhichisconsumedbythejsp.

ThepopulateFeesInfomethodperformsthefollowingtasks:

Cooksupthedynamicselectqueryforagivenstudentid.

GetsthedatabaseconnectionfromDatabaseServiceclass.

Createsthestatementandexecutesthequery.

PopulatestheStudeneFeesBeaninstancefromtheResultSetandaddsdatarelatedtostudentfees.

StudentFeesBean.java

TheStudentFeessBeanclassisjustasimplejavabeanwithprivatefieldswiththeirgettersandsetters.Pleaserefertheclassdiagramandbelowsourcecodeforunderstandingthisclass.

packagecom.bis.beans;

publicclassStudentFeesBeanextendsStudentBean{

publicStudentFeesBean(){

super();

}

privatejava.lang.StringjanAcad;

privatejava.lang.StringfebAcad;

privatejava.lang.StringmarAcad;

privatejava.lang.StringaprAcad;

privatejava.lang.StringmayAcad;

privatejava.lang.StringjunAcad;

privatejava.lang.StringjulAcad;

privatejava.lang.StringaugAcad;

privatejava.lang.StringsepAcad;

privatejava.lang.StringoctAcad;

privatejava.lang.StringnovAcad;

privatejava.lang.StringdecAcad;

privatejava.lang.StringjanBus;

privatejava.lang.StringfebBus;

privatejava.lang.StringmarBus;

privatejava.lang.StringaprBus;

privatejava.lang.StringmayBus;

privatejava.lang.StringjunBus;

privatejava.lang.StringjulBus;

privatejava.lang.StringaugBus;

privatejava.lang.StringsepBus;

privatejava.lang.StringoctBus;

privatejava.lang.StringnovBus;

privatejava.lang.StringdecBus;

publicvoidsetJanAcad(StringjanAcad){

this.janAcad=janAcad;

}

publicStringgetJanAcad(){

returnjanAcad;

}

publicvoidsetFebAcad(StringfebAcad){

this.febAcad=febAcad;

}

publicStringgetFebAcad(){

returnfebAcad;

}

publicvoidsetMarAcad(StringmarAcad){

this.marAcad=marAcad;

}

publicStringgetMarAcad(){

returnmarAcad;

}

publicvoidsetAprAcad(StringaprAcad){

this.aprAcad=aprAcad;

}

publicStringgetAprAcad(){

returnaprAcad;

}

publicvoidsetMayAcad(StringmayAcad){

this.mayAcad=mayAcad;

}

publicStringgetMayAcad(){

returnmayAcad;

}

publicvoidsetJunAcad(StringjunAcad){

this.junAcad=junAcad;

}

publicStringgetJunAcad(){

returnjunAcad;

}

publicvoidsetJulAcad(StringjulAcad){

this.julAcad=julAcad;

}

publicStringgetJulAcad(){

returnjulAcad;

}

publicvoidsetAugAcad(StringaugAcad){

this.augAcad=augAcad;

}

publicStringgetAugAcad(){

returnaugAcad;

}

publicvoidsetSepAcad(StringsepAcad){

this.sepAcad=sepAcad;

}

publicStringgetSepAcad(){

returnsepAcad;

}

publicvoidsetOctAcad(StringoctAcad){

this.octAcad=octAcad;

}

publicStringgetOctAcad(){

returnoctAcad;

}

publicvoidsetNovAcad(StringnovAcad){

this.novAcad=novAcad;

}

publicStringgetNovAcad(){

returnnovAcad;

}

publicvoidsetDecAcad(StringdecAcad){

this.decAcad=decAcad;

}

publicStringgetDecAcad(){

returndecAcad;

}

publicvoidsetJanBus(StringjanBus){

this.janBus=janBus;

}

publicStringgetJanBus(){

returnjanBus;

}

publicvoidsetFebBus(StringfebBus){

this.febBus=febBus;

}

publicStringgetFebBus(){

returnfebBus;

}

publicvoidsetMarBus(StringmarBus){

this.marBus=marBus;

}

publicStringgetMarBus(){

returnmarBus;

}

publicvoidsetAprBus(StringaprBus){

this.aprBus=aprBus;

}

publicStringgetAprBus(){

returnaprBus;

}

publicvoidsetMayBus(StringmayBus){

this.mayBus=mayBus;

}

publicStringgetMayBus(){

returnmayBus;

}

publicvoidsetJunBus(StringjunBus){

this.junBus=junBus;

}

publicStringgetJunBus(){

returnjunBus;

}

publicvoidsetJulBus(StringjulBus){

this.julBus=julBus;

}

publicStringgetJulBus(){

returnjulBus;

}

publicvoidsetAugBus(StringaugBus){

this.augBus=augBus;

}

publicStringgetAugBus(){

returnaugBus;

}

publicvoidsetSepBus(StringsepBus){

this.sepBus=sepBus;

}

publicStringgetSepBus(){

returnsepBus;

}

publicvoidsetOctBus(StringoctBus){

this.octBus=octBus;

}

publicStringgetOctBus(){

returnoctBus;

}

publicvoidsetNovBus(StringnovBus){

this.novBus=novBus;

}

publicStringgetNovBus(){

returnnovBus;

}

publicvoidsetDecBus(StringdecBus){

this.decBus=decBus;

}

publicStringgetDecBus(){

returndecBus;

}

}

StudentFees.jsp

ThisjspisdynamicallyincludedinBisHome.jspasaresultforgetstudentfeesusecaseinvocationthroughuserinteractionwiththeUI.

TillnowwehaveseenthatthecommandforstudentfeesgoesformUIasaresultofuserinteraction.Thenthecontrollerservletcallsgetstudentfeescommandprocessorandthenthestudentfeesserviceisleveraged.Finally,wegettheresultspackagedasaninstanceofStudentFeesBean.Thisbeanisnowavailableinthesession.IntheStudentFees.jspfilewefetchthisbeanfromthesession.Andfromthisbeanwefetchalltheinformationrelatedtostudentfeesusingthegetters.Thestaticpartofthejspremainsthesameasthatoftheprototypepage.Onlythedynamicpartisaddedusingthebeanfromthesession.Hence,theenduserseestheviewwiththefeesdetailsforagivenstudent.

HereisthesourcecodefortheStudentFees.jspfile.

<%@pageimport=“com.bis.beans.StudentFeesBean,com.bis.beans.StudentResultsBean”%>

<%@pageimport=“java.util.Hashtable,java.util.Enumeration”%>

<%

StudentFeesBeanstudentFeesBean=null;

StudentResultsBeanstudentResultsBean=null;

if(session!=null){

studentFeesBean=(StudentFeesBean)session.getAttribute(“studentFeesBean”);

studentResultsBean=(StudentResultsBean)session.getAttribute(“studentResultsBean”);

}

%>

<formid=“frmStudentFees”>

<tableborder=“0”cellpadding=“0”cellspacing=“0”width=“100%”height=“99%”>

<tr>

<tdwidht=”*”align=“center”valign=“top”>

<tableborder=“0”cellpadding=“10”cellspacing=“0”width=“100%”>

<tr><td>&nbsp;</td></tr>

<tr>

<tdbgcolor=“White”align=“center”colspan=“3”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getFullName());

}

%>

&nbsp;&nbsp;|&nbsp;&nbsp;

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getGrade());

out.print(”-“);

out.print(studentResultsBean.getSection());

}

%>

&nbsp;&nbsp;|&nbsp;&nbsp;

<%

if(studentResultsBean!=null){

out.print(studentFeesBean.getStudentId());

}

%>

&nbsp;&nbsp;

</td>

</tr>

<tr><td>&nbsp;</td></tr>

<trvalign=“middle”>

<tdalign=“center”>

<tableborder=“1”cellpadding=“10”cellspacing=“0”width=“80%”bgcolor=“White”>

<trid=“trbgred”>

<tdcolspan=“12”align=“left”>

&nbsp;&nbsp;AcademicFees

</td>

</tr>

<trid=“clred”>

<tdcolspan=“3”align=“center”>

TermOne

</td>

<tdcolspan=“3”align=“center”>

TermTwo

</td>

<tdcolspan=“3”align=“center”>

TermThree

</td>

<tdcolspan=“3”align=“center”>

TermFour

</td>

</tr>

<trid=“clred”>

<tdalign=“center”width=“8%”>

April

</td>

<tdalign=“center”width=“8%”>

May

</td>

<tdalign=“center”width=“8%”>

June

</td>

<tdalign=“center”width=“8%”>

July

</td>

<tdalign=“center”width=“8%”>

August

</td>

<tdalign=“center”width=“8%”>

September

</td>

<tdalign=“center”width=“8%”>

October

</td>

<tdalign=“center”width=“8%”>

November

</td>

<tdalign=“center”width=“8%”>

December

</td>

<tdalign=“center”width=“8%”>

January

</td>

<tdalign=“center”width=“8%”>

February

</td>

<tdalign=“center”width=“8%”>

March

</td>

</tr>

<tr>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getAprAcad());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getMayAcad());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getJunAcad());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getJulAcad());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getAugAcad());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getSepAcad());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getOctAcad());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getNovAcad());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getDecAcad());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getJanAcad());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getFebAcad());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getMarAcad());

}

%>

</td>

</tr>

</table>

</td>

</tr>

<trvalign=“middle”>

<tdalign=“center”>

<tableborder=“1”cellpadding=“10”cellspacing=“0”width=“80%”bgcolor=“White”>

<trid=“trbgred”>

<tdcolspan=“12”align=“left”>

<fontsize=“4”>

&nbsp;&nbsp;BusFees

</font>

</td>

</tr>

<trid=“clred”>

<tdalign=“center”width=“8%”>

April

</td>

<tdalign=“center”width=“8%”>

May

</td>

<tdalign=“center”width=“8%”>

June

</td>

<tdalign=“center”width=“8%”>

July

</td>

<tdalign=“center”width=“8%”>

August

</td>

<tdalign=“center”width=“8%”>

September

</td>

<tdalign=“center”width=“8%”>

October

</td>

<tdalign=“center”width=“8%”>

November

</td>

<tdalign=“center”width=“8%”>

December

</td>

<tdalign=“center”width=“8%”>

January

</td>

<tdalign=“center”width=“8%”>

February

</td>

<tdalign=“center”width=“8%”>

March

</td>

</tr>

<tr>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getAprBus());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getMayBus());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getJunBus());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getJulBus());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getAugBus());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getSepBus());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getOctBus());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getNovBus());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getDecBus());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getJanBus());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getFebBus());

}

%>

</td>

<tdalign=“center”>

<%

if(studentFeesBean!=null){

out.print(studentFeesBean.getMarBus());

}

%>

</td>

</tr>

</table>

</td>

</tr>

<trvalign=“middle”>

<tdalign=“center”>

<tableborder=“1”cellpadding=“10”cellspacing=“0”width=“80%”bgcolor=“White”>

<trid=“trbgred”>

<tdalign=“left”>

&nbsp;&nbsp;OtherFees

</td>

</tr>

<tr>

<tdalign=“left”>

&nbsp;

</td>

</tr>

</table>

</td>

</tr>

<tr><td>&nbsp;</td></tr>

</table>

</td>

</tr>

</table>

</form>

Thisconcludesthegetstudentfeesusecaseimplementationfromendtoend.Wecomposedtherequirementspecifications,webuilttheprototype,wefollowedthearchitectureforthesolution,weleveragedtheframework,wedevelopedthevariousjavaclasses,weusedthecommoncomponentslikeDatabaseService.java,BISStyle.cssetcandwebuilttheviewwiththejsppage.

UseCase:Getstudentresults.

RequirementsSpecificationReference:R6

PrototypeReference:P5

Prerequisite:Thestudenthastobeloadedintocontextfirst.

Thisusecaseneedstobeimplementedaspertherequirementsspecificationreferenceabove.TheUIneedstobeaspertheprototypereferenceabove.NowthatwehavecompleteclarityonusecaserequirementsandUIwewillnowproceedtoimplementthisusecase.

Inordertoimplementthisusecase,weneedtofollowthearchitectureandleveragetheframework.Toachievethiswewillfirstcomeupwithdetaileddesignandthencodeit.

Theprerequisiteforthisusecaseisthatastudentmustalreadybeexistinginthecontext,forthistheusermusthaveloadedthestudentthroughtheloadstudentusecase.Whenthestudentisloaded,thestudentidofaparticularstudentisaddedtothesession.Youcanrefertheloadstudentusecasefordetailsonthis.Letsassumeasofnowthatthestudentidisexistinginthehttpsession.Whentheuserclicksongetstudentresult(eitherforsemesterIorforsemesterII)linkeitherondashboardorviathemenu,thefollowingflowistriggered.

Getstudentresultlinkisclicked.

ThehreffortheselinksareBisControllerServlet?ParameterActionCommand=GetStudentAcademics&sem=1andBisControllerServlet?ParameterActionCommand=GetStudentAcademics&sem=2

TheControllerServletisinvokedontheserver

IntheservicemethodtheactioncommandparametervalueisreadwhichisGetStudentAcademics.

TheexecutemethodforthecommandprocessorpertainingtoGetStudentAcademicsisinvoked.

Thebusinesslogicpertainingtothiscommandprocessorisexecutedandaviewisreturned.

Theresponseisreturnedtothebrowserwiththisview.

Theuserseesthestudentresultspageforagivensemester.

ThecommandprocessorclasspertainingtoGetStudentAcademicscommandisGetStudentAcademicsCP.TheviewpertainingtostudentdetailpageisStudentAcademics.jsp.ReferthecodebelowtoseethesequenceofmethodcallsoncetheexecutemethodofGetStudentAcademicsCPiscalled.

Forthisusecaseweneedthefollowingfiles.

1.GetStudentAcademicsCP.java

2.StudentAcademicsService.java

3.StudentResultsBean.java

4.StudentAcademics.jsp

GetStudentAcademicsCP.java

packagecom.bis.cp;

importcom.bis.session.StudentAcademicsService;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importjavax.servlet.http.HttpSession;

importorg.apache.log4j.Logger;

publicclassGetStudentAcademicsCPextendsBisCPimplementsBisCommand{

staticLoggerlogger=Logger.getLogger(GetStudentAcademicsCP.class);

publicGetStudentAcademicsCP(){

super();

}

publicStringexecute(HttpServletRequestrequest,HttpServletResponseresponse){

HttpSessionsession=request.getSession();

StringstrStudentId;

StringstrSemester=“1”;//Defaultingsemestertofirst.

strSemester=request.getParameter(“sem”);

if(session!=null){

strStudentId=(String)session.getAttribute(“StudentId”);

if(strStudentId!=null&&!(strStudentId.trim().equalsIgnoreCase(””))){

StudentAcademicsServicestudentAcademicsService=newStudentAcademicsService();

try{

studentAcademicsService.processGetStudentResults(session,strSemester);

strNextNavigation=“StudentAcademics”;//Thenextnavigationpageuponsuccessfulprocessing.

}catch(Exceptione){

logger.error(e.getMessage());

strNextNavigation=“Error”;//Thenextnavigationpageuponfailedprocessing.

}

}

else{

//strStudentIdisnull,firstentrytothepage.

strNextNavigation=“StudentAcademics”;

}

}

else{

//sessionisnull.Validsessiondoesn’texsit.RedirecttoLoginpage.

strNextNavigation=“Login”;

}

returnstrNextNavigation;

}

}

Theexecutemethodperformsthefollowingactions:

GetstheHttpsessionfortheloggedinuser.

Getsthesemestertheuserhasselectedasaparametervalue.

Getsthestudentidfromthesession.

CreatesaninstanceofStudentAcademicsServiceandinvokesprocessGetStudentResultsmethod.

SetsthenextnavigationtoStudentAcademics.

StudentAcademicsService.java

packagecom.bis.session;

importcom.bis.beans.StudentResultsBean;

importcom.bis.db.DatabaseService;

importjava.sql.Connection;

importjava.sql.ResultSet;

importjava.sql.SQLException;

importjava.sql.Statement;

importjavax.servlet.http.HttpSession;

importorg.apache.log4j.Logger;

publicclassStudentAcademicsServiceimplementsBisService{

staticLoggerlogger=Logger.getLogger(StudentAcademicsService.class);

publicStudentAcademicsService(){

super();

}

publicvoidprocessGetStudentResults(HttpSessionsession,StringstrSemester){

StringstrStudentId=(String)session.getAttribute(“StudentId”);

StudentResultsBeanstudentResultsBean;

studentResultsBean=newStudentResultsBean();

if(strStudentId!=null){

studentResultsBean.setStudentId(strStudentId);//Thisismandatorybeforecallingthenextmethod.

populateStudentResults(studentResultsBean,strSemester);

session.setAttribute(“studentResultsBean”,studentResultsBean);

}else{

logger.error(“StudentIdisnull”);

}

}

privatevoidpopulateStudentResults(StudentResultsBeanstudentResultsBean,StringstrSemester){

StringstrStudentId;

strStudentId=studentResultsBean.getStudentId();

Connectionconnection=null;

Statementstatement=null;

ResultSetresultSet=null;

StringBuffersbQuery=newStringBuffer();

StringstrFirstName=””;

StringstrMiddleName=””;

StringstrLastName=””;

StringstrFullName=””;

sbQuery.append(“SELECT\n”+

“SD.FIRST_NAME,SD.MIDDLE_NAME,SD.LAST_NAME,SD.GRADE,SD.SECTION,\n”+

“SR.ENGLISH_GRADE,SR.MATHS_GRADE,SR.SCIENCE_GRADE,SR.SOCIAL_GRADE,\n”+

“SR.LANG2_GRADE,SR.LANG3_GRADE,SR.COMPSC_GRADE,SR.ARTS_GRADE,\n”+

“SR.MUSIC_GRADE,SR.DANCE_GRADE,SR.PHYSICALEDU_GRADE,SR.VALUEEDU_GRADE,\n”+

“SR.SCHOOLPROJECT_GRADE,\n”+

“SR.ENGLISH_REM,SR.MATHS_REM,SR.SCIENCE_REM,SR.SOCIAL_REM,\n”+

“SR.LANG2_REM,SR.LANG3_REM,SR.COMPSC_REM,SR.ARTS_REM,\n”+

“SR.MUSIC_REM,SR.DANCE_REM,SR.PHYSICALEDU_REM,SR.VALUEEDU_REM,\n”+

“SR.SCHOOLPROJECT_REM,\n”+

“CSR.COLLAB_LEARNING,CSR.COMMUNICATION_SKILLS,CSR.COMMUNITY_CONSC,\n”+

“CSR.COMPREHENSIVE_GROWTH,CSR.CREATIVE_THINKING,CSR.CRITICAL_THINKING,\n”+

“CSR.EMO_QUO,CSR.HEALTH_QUO,CSR.INTELLI_QUO,CSR.SOCIAL_QUO,\n”+

“CSR.SCHOLASTICPERFORMANCE_REM,CSR.COSCHOLASTICPERFORMANCE_REM\n”+

“FROM\n”+

“STUDENT_DETAILSSD,SCHOLASTIC_RESULTSSR,COSCHOLASTIC_RESULTSCSR\n”+

“\n”+

“WHERE\n”+

“SD.STUDENT_ID=“);

sbQuery.append(”’”+strStudentId+”’“);

sbQuery.append(“ANDSR.STUDENT_ID=“);

sbQuery.append(”’”+strStudentId+”’“);

sbQuery.append(”ANDSR.SEMESTER=“);

sbQuery.append(”’”+strSemester+”’“);

sbQuery.append(“ANDCSR.STUDENT_ID=“);

sbQuery.append(”’”+strStudentId+”’“);

sbQuery.append(”ANDCSR.SEMESTER=“);

sbQuery.append(”’”+strSemester+”’“);

if(strStudentId!=null){

connection=DatabaseService.getDBConnection();

try{

statement=connection.createStatement();

resultSet=statement.executeQuery(sbQuery.toString());

resultSet.next();//Expectingonlyonerecord.

strFirstName=resultSet.getString(“FIRST_NAME”);

strMiddleName=resultSet.getString(“MIDDLE_NAME”);

strLastName=resultSet.getString(“LAST_NAME”);

if(strFirstName!=null){

strFullName=strFirstName;

}

if(strMiddleName!=null){

strFullName=strFullName+””+strMiddleName;

}

if(strLastName!=null){

strFullName=strFullName+””+strLastName;

}

studentResultsBean.setFullName(strFullName);

studentResultsBean.setGrade(resultSet.getString(“GRADE”));

studentResultsBean.setSection(resultSet.getString(“SECTION”));

studentResultsBean.setEnglishGrade(resultSet.getString(“ENGLISH_GRADE”));

studentResultsBean.setMathsGrade(resultSet.getString(“MATHS_GRADE”));

studentResultsBean.setScienceGrade(resultSet.getString(“SCIENCE_GRADE”));

studentResultsBean.setSocialGrade(resultSet.getString(“SOCIAL_GRADE”));

studentResultsBean.setLang2Grade(resultSet.getString(“LANG2_GRADE”));

studentResultsBean.setLang3Grade(resultSet.getString(“LANG3_GRADE”));

studentResultsBean.setCompScGrade(resultSet.getString(“COMPSC_GRADE”));

studentResultsBean.setArtsGrade(resultSet.getString(“ARTS_GRADE”));

studentResultsBean.setMusicGrade(resultSet.getString(“MUSIC_GRADE”));

studentResultsBean.setDanceGrade(resultSet.getString(“DANCE_GRADE”));

studentResultsBean.setPhyEduGrade(resultSet.getString(“PHYSICALEDU_GRADE”));

studentResultsBean.setValEduGrade(resultSet.getString(“VALUEEDU_GRADE”));

studentResultsBean.setSchProjGrade(resultSet.getString(“SCHOOLPROJECT_GRADE”));

studentResultsBean.setEnglishRem(resultSet.getString(“ENGLISH_REM”));

studentResultsBean.setMathsRem(resultSet.getString(“MATHS_REM”));

studentResultsBean.setScienceRem(resultSet.getString(“SCIENCE_REM”));

studentResultsBean.setSocialRem(resultSet.getString(“SOCIAL_REM”));

studentResultsBean.setLang2Rem(resultSet.getString(“LANG2_REM”));

studentResultsBean.setLang3Rem(resultSet.getString(“LANG3_REM”));

studentResultsBean.setCompScRem(resultSet.getString(“COMPSC_REM”));

studentResultsBean.setArtsRem(resultSet.getString(“ARTS_REM”));

studentResultsBean.setMusicRem(resultSet.getString(“MUSIC_REM”));

studentResultsBean.setDanceRem(resultSet.getString(“DANCE_REM”));

studentResultsBean.setPhyEduRem(resultSet.getString(“PHYSICALEDU_REM”));

studentResultsBean.setValEduRem(resultSet.getString(“VALUEEDU_REM”));

studentResultsBean.setSchProjRem(resultSet.getString(“SCHOOLPROJECT_REM”));

studentResultsBean.setCollabLearning(resultSet.getString(“COLLAB_LEARNING”));

studentResultsBean.setCommSkills(resultSet.getString(“COMMUNICATION_SKILLS”));

studentResultsBean.setCommunityConsc(resultSet.getString(“COMMUNITY_CONSC”));

studentResultsBean.setCompGrowth(resultSet.getString(“COMPREHENSIVE_GROWTH”));

studentResultsBean.setCreativeThinking(resultSet.getString(“CREATIVE_THINKING”));

studentResultsBean.setCriticalThinking(resultSet.getString(“CRITICAL_THINKING”));

studentResultsBean.setEmoQuo(resultSet.getString(“EMO_QUO”));

studentResultsBean.setHealthQuo(resultSet.getString(“HEALTH_QUO”));

studentResultsBean.setIntelliQuo(resultSet.getString(“INTELLI_QUO”));

studentResultsBean.setSocialQuo(resultSet.getString(“SOCIAL_QUO”));

studentResultsBean.setScholasticPerformanceRem(resultSet.getString(“SCHOLASTICPERFORMANCE_REM”));

studentResultsBean.setCoScholasticPerformanceRem(resultSet.getString(“COSCHOLASTICPERFORMANCE_REM”));

}catch(SQLExceptionsqle){

logger.error(sqle.getMessage());

}finally{

DatabaseService.closeDBResouces(statement,resultSet);

DatabaseService.releaseDBConnection();//Releasingdatabaseconnection.

}

}else{

logger.error(“StudentIdisnull”);

}

}

publicStringgetServiceName(){

returnthis.getClass().getName();

}

}

TheprocessGetStudentResultsmethodperformsthefollowingtasks:

Getsthestudentidfromthesession.

CreatesaninstanceofStudentResultsBean.

CallssetterofStudentResultsBeaninstanceforsettingstudentid.

InvokestheprivatemethodpopulateStudentResults.

AddsthepopulatedStudentResultsBeaninstancetosessiontobeconsumedbytheview.

ThepopulateStudentResultsmethodperformsthefollowingtasks:

Cooksupadynamicqueryforagivenstudentandsemestertofetchtheresults

fromthedatabase.

LeveragestheDatabaseServiceclasstogetthedatabaseconnection.

CallssetterofStudentResultsBeaninstanceforsettingtheresultsfields.

Usesthefinallyblocktoclosealltheresourcesrelatedtodatabase.

StudentResultsBean.java

TheStudentResultsBeanclassisjustasimplejavabeanwithprivatefieldswiththeirgettersandsetters.Pleaserefertheclassdiagramandbelowsourcecodeforunderstandingthisclass.

packagecom.bis.beans;

publicclassStudentResultsBeanextendsStudentBean{

publicStudentResultsBean(){

super();

}

privatejava.lang.StringenglishGrade;

privatejava.lang.StringmathsGrade;

privatejava.lang.StringscienceGrade;

privatejava.lang.StringsocialGrade;

privatejava.lang.Stringlang2Grade;

privatejava.lang.Stringlang3Grade;

privatejava.lang.StringcompScGrade;

privatejava.lang.StringartsGrade;

privatejava.lang.StringmusicGrade;

privatejava.lang.StringdanceGrade;

privatejava.lang.StringphyEduGrade;

privatejava.lang.StringvalEduGrade;

privatejava.lang.StringschProjGrade;

privatejava.lang.StringenglishRem;

privatejava.lang.StringmathsRem;

privatejava.lang.StringscienceRem;

privatejava.lang.StringsocialRem;

privatejava.lang.Stringlang2Rem;

privatejava.lang.Stringlang3Rem;

privatejava.lang.StringcompScRem;

privatejava.lang.StringartsRem;

privatejava.lang.StringmusicRem;

privatejava.lang.StringdanceRem;

privatejava.lang.StringphyEduRem;

privatejava.lang.StringvalEduRem;

privatejava.lang.StringschProjRem;

privatejava.lang.StringcollabLearning;

privatejava.lang.StringcommSkills;

privatejava.lang.StringcommunityConsc;

privatejava.lang.StringcompGrowth;

privatejava.lang.StringcreativeThinking;

privatejava.lang.StringcriticalThinking;

privatejava.lang.StringemoQuo;

privatejava.lang.StringhealthQuo;

privatejava.lang.StringintelliQuo;

privatejava.lang.StringsocialQuo;

privatejava.lang.StringscholasticPerformanceRem;

privatejava.lang.StringcoScholasticPerformanceRem;

publicvoidsetEnglishGrade(StringenglishGrade){

this.englishGrade=englishGrade;

}

publicStringgetEnglishGrade(){

returnenglishGrade;

}

publicvoidsetMathsGrade(StringmathsGrade){

this.mathsGrade=mathsGrade;

}

publicStringgetMathsGrade(){

returnmathsGrade;

}

publicvoidsetScienceGrade(StringscienceGrade){

this.scienceGrade=scienceGrade;

}

publicStringgetScienceGrade(){

returnscienceGrade;

}

publicvoidsetSocialGrade(StringsocialGrade){

this.socialGrade=socialGrade;

}

publicStringgetSocialGrade(){

returnsocialGrade;

}

publicvoidsetLang2Grade(Stringlang2Grade){

this.lang2Grade=lang2Grade;

}

publicStringgetLang2Grade(){

returnlang2Grade;

}

publicvoidsetLang3Grade(Stringlang3Grade){

this.lang3Grade=lang3Grade;

}

publicStringgetLang3Grade(){

returnlang3Grade;

}

publicvoidsetCompScGrade(StringcompScGrade){

this.compScGrade=compScGrade;

}

publicStringgetCompScGrade(){

returncompScGrade;

}

publicvoidsetArtsGrade(StringartsGrade){

this.artsGrade=artsGrade;

}

publicStringgetArtsGrade(){

returnartsGrade;

}

publicvoidsetMusicGrade(StringmusicGrade){

this.musicGrade=musicGrade;

}

publicStringgetMusicGrade(){

returnmusicGrade;

}

publicvoidsetDanceGrade(StringdanceGrade){

this.danceGrade=danceGrade;

}

publicStringgetDanceGrade(){

returndanceGrade;

}

publicvoidsetPhyEduGrade(StringphyEduGrade){

this.phyEduGrade=phyEduGrade;

}

publicStringgetPhyEduGrade(){

returnphyEduGrade;

}

publicvoidsetValEduGrade(StringvalEduGrade){

this.valEduGrade=valEduGrade;

}

publicStringgetValEduGrade(){

returnvalEduGrade;

}

publicvoidsetSchProjGrade(StringschProjGrade){

this.schProjGrade=schProjGrade;

}

publicStringgetSchProjGrade(){

returnschProjGrade;

}

publicvoidsetEnglishRem(StringenglishRem){

this.englishRem=englishRem;

}

publicStringgetEnglishRem(){

returnenglishRem;

}

publicvoidsetMathsRem(StringmathsRem){

this.mathsRem=mathsRem;

}

publicStringgetMathsRem(){

returnmathsRem;

}

publicvoidsetScienceRem(StringscienceRem){

this.scienceRem=scienceRem;

}

publicStringgetScienceRem(){

returnscienceRem;

}

publicvoidsetSocialRem(StringsocialRem){

this.socialRem=socialRem;

}

publicStringgetSocialRem(){

returnsocialRem;

}

publicvoidsetLang2Rem(Stringlang2Rem){

this.lang2Rem=lang2Rem;

}

publicStringgetLang2Rem(){

returnlang2Rem;

}

publicvoidsetLang3Rem(Stringlang3Rem){

this.lang3Rem=lang3Rem;

}

publicStringgetLang3Rem(){

returnlang3Rem;

}

publicvoidsetCompScRem(StringcompScRem){

this.compScRem=compScRem;

}

publicStringgetCompScRem(){

returncompScRem;

}

publicvoidsetArtsRem(StringartsRem){

this.artsRem=artsRem;

}

publicStringgetArtsRem(){

returnartsRem;

}

publicvoidsetMusicRem(StringmusicRem){

this.musicRem=musicRem;

}

publicStringgetMusicRem(){

returnmusicRem;

}

publicvoidsetDanceRem(StringdanceRem){

this.danceRem=danceRem;

}

publicStringgetDanceRem(){

returndanceRem;

}

publicvoidsetPhyEduRem(StringphyEduRem){

this.phyEduRem=phyEduRem;

}

publicStringgetPhyEduRem(){

returnphyEduRem;

}

publicvoidsetValEduRem(StringvalEduRem){

this.valEduRem=valEduRem;

}

publicStringgetValEduRem(){

returnvalEduRem;

}

publicvoidsetSchProjRem(StringschProjRem){

this.schProjRem=schProjRem;

}

publicStringgetSchProjRem(){

returnschProjRem;

}

publicvoidsetCollabLearning(StringcollabLearning){

this.collabLearning=collabLearning;

}

publicStringgetCollabLearning(){

returncollabLearning;

}

publicvoidsetCommSkills(StringcommSkills){

this.commSkills=commSkills;

}

publicStringgetCommSkills(){

returncommSkills;

}

publicvoidsetCommunityConsc(StringcommunityConsc){

this.communityConsc=communityConsc;

}

publicStringgetCommunityConsc(){

returncommunityConsc;

}

publicvoidsetCompGrowth(StringcompGrowth){

this.compGrowth=compGrowth;

}

publicStringgetCompGrowth(){

returncompGrowth;

}

publicvoidsetCreativeThinking(StringcreativeThinking){

this.creativeThinking=creativeThinking;

}

publicStringgetCreativeThinking(){

returncreativeThinking;

}

publicvoidsetCriticalThinking(StringcriticalThinking){

this.criticalThinking=criticalThinking;

}

publicStringgetCriticalThinking(){

returncriticalThinking;

}

publicvoidsetEmoQuo(StringemoQuo){

this.emoQuo=emoQuo;

}

publicStringgetEmoQuo(){

returnemoQuo;

}

publicvoidsetHealthQuo(StringhealthQuo){

this.healthQuo=healthQuo;

}

publicStringgetHealthQuo(){

returnhealthQuo;

}

publicvoidsetIntelliQuo(StringintelliQuo){

this.intelliQuo=intelliQuo;

}

publicStringgetIntelliQuo(){

returnintelliQuo;

}

publicvoidsetSocialQuo(StringsocialQuo){

this.socialQuo=socialQuo;

}

publicStringgetSocialQuo(){

returnsocialQuo;

}

publicvoidsetScholasticPerformanceRem(StringscholasticPerformanceRem){

this.scholasticPerformanceRem=scholasticPerformanceRem;

}

publicStringgetScholasticPerformanceRem(){

returnscholasticPerformanceRem;

}

publicvoidsetCoScholasticPerformanceRem(StringcoScholasticPerformanceRem){

this.coScholasticPerformanceRem=coScholasticPerformanceRem;

}

publicStringgetCoScholasticPerformanceRem(){

returncoScholasticPerformanceRem;

}

}

StudentAcademics.jsp

ThisjspisdynamicallyincludedinBisHome.jspasaresultforgetstudentresultsusecaseinvocationthroughuserinteractionwiththeUI.

TillnowwehaveseenthatthecommandforstudentresultsgoesformUIasaresultofuserinteraction.Thenthecontrollerservletcallsgetstudentacademicscommandprocessorandthenthestudentacademicsserviceisleveraged.Finally,wegettheresultspackagedasaninstanceofStudentResultsBean.Thisbeanisnowavailableinthesession.IntheStudentAcademics.jspfilewefetchthisbeanfromthesession.Andfromthisbeanwefetchalltheinformationrelatedtostudentresultsusingthegetters.Thestaticpartofthejspremainsthesameasthatoftheprototypepage.Onlythedynamicpartisaddedusingthebeanfromthesession.Hence,theenduserseestheviewforagivenstudentandsemesterwithalltheacademicresultsrelateddetails.

HereisthesourcecodefortheStudentAcademics.jspfile.

<%@pageimport=“com.bis.beans.StudentResultsBean”%>

<%@pageimport=“java.util.Hashtable,java.util.Enumeration”%>

<%

StudentResultsBeanstudentResultsBean=null;

if(session!=null){

studentResultsBean=(StudentResultsBean)session.getAttribute(“studentResultsBean”);

}

%>

<formid=“frmStudAcads”name=“frmStudAcads”action=“BisControllerServlet”method=“POST”>

<inputtype=“hidden”name=“ParameterActionCommand”value=“GetStudentAcademics”></input>

<inputtype=“hidden”name=“sem”value=”<%=request.getParameter(“sem”)%>”></input>

<tableborder=“0”cellpadding=“0”cellspacing=“0”width=“100%”height=“99%”>

<tr><td>&nbsp;</td></tr>

<tr><td>&nbsp;</td></tr>

<tr>

<tdwidht=”*”align=“center”valign=“top”>

<tableborder=“0”cellpadding=“4”cellspacing=“0”width=“100%”>

<tr>

<tdbgcolor=“White”align=“center”colspan=“3”>

<fontsize=“4”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getFullName());

}

%>

&nbsp;&nbsp;|&nbsp;&nbsp;

<%

StringstrSem=request.getParameter(“sem”);

if(strSem!=null){

if(strSem.equalsIgnoreCase(“1”)){

strSem=“Semester-I”;

}

else{

strSem=“Semester-II”;

}

}

else{

strSem=“Semester-I”;

}

out.print(strSem);

%>

&nbsp;&nbsp;|&nbsp;&nbsp;

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getGrade());

out.print(”-“);

out.print(studentResultsBean.getSection());

}

%>

&nbsp;&nbsp;|&nbsp;&nbsp;

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getStudentId());

}

%>

&nbsp;&nbsp;

</font>

</td>

</tr>

<tr><td>&nbsp;</td></tr>

<tr><td>&nbsp;</td></tr>

<trvalign=“top”>

<tdalign=“left”width=“50%”>

<tableborder=“1”cellpadding=“5”cellspacing=“0”width=“100%”bgcolor=“White”>

<tr>

<tdcolspan=“3”align=“center”id=“trbgred”>

ScholasticPerformance-CoreCurriculum-Assessment

</td>

</tr>

<trid=“clred”>

<tdwidth=“20%”align=“center”>&nbsp;&nbsp;Subject</td>

<tdwidth=“10%”align=“center”>Grade</td>

<tdwidth=”*”align=“center”>Remarks</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;English</td>

<tdalign=“center”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getEnglishGrade());

}

%>

</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getEnglishRem());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;Mathematics</td>

<tdalign=“center”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getMathsGrade());

}

%>

</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getMathsRem());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;Science</td>

<tdalign=“center”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getScienceGrade());

}

%>

</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getScienceRem());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;SocialScience</td>

<tdalign=“center”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getSocialGrade());

}

%>

</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getSocialRem());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;LanguageII</td>

<tdalign=“center”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getLang2Grade());

}

%>

</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getLang2Rem());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;LanguageIII</td>

<tdalign=“center”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getLang3Grade());

}

%>

</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getLang3Rem());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;ComputerScience</td>

<tdalign=“center”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getCompScGrade());

}

%>

</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getCompScRem());

}

%>

</td>

</tr>

</table>

</td>

<tdalign=“left”width=”*”colspan=“2”>

<tableborder=“1”cellpadding=“5”cellspacing=“0”width=“100%”bgcolor=“White”>

<tr>

<tdcolspan=“3”align=“center”id=“trbgred”>ScholasticPerformance-CoCurriculum-

Assessment</td>

</tr>

<trid=“clred”>

<tdwidth=“20%”align=“center”>&nbsp;&nbsp;Subject</td>

<tdwidth=“10%”align=“center”>Grade</td>

<tdwidth=”*”align=“center”>Remarks</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;Arts</td>

<tdalign=“center”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getArtsGrade());

}

%>

</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getArtsRem());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;Music</td>

<tdalign=“center”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getMusicGrade());

}

%>

</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getMusicRem());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;Dance</td>

<tdalign=“center”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getDanceGrade());

}

%>

</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getDanceRem());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;PhysicalEducation</td>

<tdalign=“center”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getPhyEduGrade());

}

%>

</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getPhyEduRem());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;ValueEducation</td>

<tdalign=“center”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getValEduGrade());

}

%>

</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getValEduRem());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;SchoolProject</td>

<tdalign=“center”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getSchProjGrade());

}

%>

</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getSchProjRem());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;Other</td>

<tdalign=“center”>-</td>

<tdalign=“left”>-</td>

</tr>

</table>

</td>

</tr>

<trvalign=“top”>

<tdalign=“left”width=“50%”>

<tableborder=“1”cellpadding=“5”cellspacing=“0”width=“100%”bgcolor=“White”>

<tr>

<tdcolspan=“2”align=“center”id=“trbgred”>Co-ScholasticActivities</td>

</tr>

<tr>

<tdalign=“left”id=“clred”width=“30%”>&nbsp;&nbsp;CriticalThinking</td>

<tdalign=“left”width=”*”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getCreativeThinking());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;CreativeThinking</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getCreativeThinking());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;CollaborativeLearning</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getCollabLearning());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;CommunicationSkills</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getCommSkills());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;ComprehensiveGrowth</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getCompGrowth());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;IQ-IntelligenceQuotient</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getIntelliQuo());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;EQ-EmotionalQuotient</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getEmoQuo());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;EQ-SocialQuotient</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getSocialQuo());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;EQ-HealthQuotient</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getHealthQuo());

}

%>

</td>

</tr>

<tr>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;EQ-CommunityConsciousness</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getCommunityConsc());

}

%>

</td>

</tr>

</table>

</td>

<tdwidth=”*”valign=“top”>

<tableborder=“1”cellpadding=“5”cellspacing=“0”width=“100%”bgcolor=“White”>

<tr>

<tdcolspan=“2”align=“center”id=“trbgred”>SynthesisandRecommendations</td>

</tr>

<trheight=“152”valign=“top”>

<tdalign=“left”width=“30%”id=“clred”>&nbsp;&nbsp;ScholasticPerformance</td>

<tdwidth=”*”align=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getScholasticPerformanceRem());

}

%>

</td>

</tr>

<trheight=“152”valign=“top”>

<tdalign=“left”id=“clred”>&nbsp;&nbsp;Co-ScholasticPerformance</td>

<tdalign=“left”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getCoScholasticPerformanceRem());

}

%>

</td>

</tr>

</table>

</td>

</tr>

</table>

</td>

</tr>

<tr><td>&nbsp;</td></tr>

<tr><td>&nbsp;</td></tr>

</table>

</form>

Thisconcludesthegetstudentresultsusecaseimplementationfromendtoend.Wecomposedtherequirementspecifications,webuilttheprototype,wefollowedthearchitectureforthesolution,weleveragedtheframework,wedevelopedthevariousjavaclasses,weusedthecommoncomponentslikeDatabaseService.java,BISStyle.cssetcandwebuilttheviewwiththejsppage.

UseCase:Helppages.

RequirementsSpecificationReference:R12

PrototypeReference:P11

Prerequisite:Theuserhastobeloggedin.

Thisusecaseneedstobeimplementedaspertherequirementsspecificationreferenceabove.TheUIneedstobeaspertheprototypereferenceabove.NowthatwehavecompleteclarityonusecaserequirementsandUIwewillnowproceedtoimplementthisusecase.

Inordertoimplementthisusecase,wejustneedtoaddalinktothedashboardpageaswellhastotheglobalHelpmenu.Thesearejustplainstatichtmlpagesandhencewedonottriggeranybusinesslogicflowontheserverside.Thehtmllinkonlyloadstherequestedhtmlpagefromthepublic_htmlfolderundertheexplodedapplicationfolderwhendeployedinApacheTomcatserver.Inoursampleapplicationwehaveonlyonestatichtmlpageforhelpmodule.Andthispagewillbedisplayedasapopupwindow.

Getlegendshelppagelinkisclicked.

Thehrefforthelinkis\bis\jsp\ResultsLegend.html

TherequestedpageResultsLegend.htmlisdisplayedasapopupwindow.

ForthisusecaseweneedonlyonehtmlpageandthatisResultsLegend.html

BisHome.jspcodeforlaunchingresultslegendhtmlpagepopupwindow.

<aonclick=“javascript:voidwindow.open(‘ResultsLegend.html’,‘1247’,‘width=1600,height=800,toolbar=0,menubar=0,location=100,status=0,scrollbars=0,resizable=1,left=180,top=140’);returnfalse;”><span>Legend</span>

</a>

ResultsLegend.html

<!DOCTYPEhtml>

<html>

<head>

<title>BISHelpLegend</title>

<linkrel=“stylesheet”type=“text/css”href=“resources/css/BISStyle.css”></link>

</head>

<body>

<formid=“frmHome”>

<tableborder=“0”cellpadding=“0”cellspacing=“0”width=“100%”height=“99%”><tr>

<tdwidht=”*”align=“center”valign=“top”>

<tableborder=“1”cellpadding=“10”cellspacing=“0”width=“100%”>

<tr>

<tdbgcolor=“White”align=“center”id=“clred”colspan=“3”>

<fontsize=“4”>Help-Legend</font>

</td>

</tr>

<trvalign=“middle”>

<tdalign=“center”>

<tableborder=“1”cellpadding=“4”cellspacing=“0”width=“80%”bgcolor=“White”>

<trid=“trbgred”>

<tdcolspan=“12”align=“left”>

<fontsize=“4”>

&nbsp;&nbsp;ScholasticPerformance-CoreCurriculum

</font>

</td>

</tr>

<tr>

<tdalign=“center”>

MarksRange

</td>

<tdalign=“center”>

AbsoluteGrade

</td>

<tdalign=“center”>

GradePoint

</td>

</tr>

<tr>

<tdalign=“center”>

81-100

</td>

<tdalign=“center”>

A

</td>

<tdalign=“center”>

10

</td>

</tr>

<tr>

<tdalign=“center”>

61-80

</td>

<tdalign=“center”>

B

</td>

<tdalign=“center”>

8

</td>

</tr>

<tr>

<tdalign=“center”>

41-60

</td>

<tdalign=“center”>

C

</td>

<tdalign=“center”>

6

</td>

</tr>

<tr>

<tdalign=“center”>

21-40

</td>

<tdalign=“center”>

D

</td>

<tdalign=“center”>

4

</td>

</tr>

<tr>

<tdalign=“center”>

00-20

</td>

<tdalign=“center”>

E

</td>

<tdalign=“center”>

-

</td>

</tr>

</table>

</td>

</tr>

<trvalign=“middle”>

<tdalign=“center”>

<tableborder=“1”cellpadding=“4”cellspacing=“0”width=“80%”bgcolor=“White”>

<trid=“trbgred”>

<tdcolspan=“12”align=“left”>

<fontsize=“4”>

&nbsp;&nbsp;ScholasticPerformance-CoCurriculum

</font>

</td>

</tr>

<tr>

<tdalign=“center”width=”*”>

Music

</td>

<tdalign=“center”width=“15%”>

A+

</td>

<tdalign=“center”width=“15%”>

A

</td>

<tdalign=“center”width=“15%”>

B+

</td>

<tdalign=“center”width=“15%”>

B

</td>

<tdalign=“center”width=“15%”>

C

</td>

</tr>

<tr>

<tdalign=“center”>

Dance

</td>

<tdalign=“center”>

A+

</td>

<tdalign=“center”>

A

</td>

<tdalign=“center”>

B+

</td>

<tdalign=“center”>

B

</td>

<tdalign=“center”>

C

</td>

</tr>

<tr>

<tdalign=“center”>

Arts

</td>

<tdalign=“center”>

A+

</td>

<tdalign=“center”>

A

</td>

<tdalign=“center”>

B+

</td>

<tdalign=“center”>

B

</td>

<tdalign=“center”>

C

</td>

</tr>

<tr>

<tdalign=“center”>

PhysicalEducation

</td>

<tdalign=“center”>

A+

</td>

<tdalign=“center”>

A

</td>

<tdalign=“center”>

B+

</td>

<tdalign=“center”>

B

</td>

<tdalign=“center”>

C

</td>

</tr>

<tr>

<tdalign=“center”>

ValueEducation

</td>

<tdalign=“center”>

A+

</td>

<tdalign=“center”>

A

</td>

<tdalign=“center”>

B+

</td>

<tdalign=“center”>

B

</td>

<tdalign=“center”>

C

</td>

</tr>

</table>

</td>

</tr>

<trvalign=“middle”>

<tdalign=“center”>

<tableborder=“1”cellpadding=“4”cellspacing=“0”width=“80%”bgcolor=“White”>

<trid=“trbgred”>

<tdcolspan=“12”align=“left”>

<fontsize=“4”>

&nbsp;&nbsp;Co-Curriculum

</font>

</td>

</tr>

<tr>

<tdalign=“center”>

Code

</td>

<tdalign=“center”>

Description

</td>

<tdalign=“center”>

Score

</td>

</tr>

<tr>

<tdalign=“center”>

LA

</td>

<tdalign=“center”>

Latent

</td>

<tdalign=“center”>

&lt;3

</td>

</tr>

<tr>

<tdalign=“center”>

EM

</td>

<tdalign=“center”>

Emerging

</td>

<tdalign=“center”>

4-5

</td>

</tr>

<tr>

<tdalign=“center”>

DE

</td>

<tdalign=“center”>

Developing

</td>

<tdalign=“center”>

6-8

</td>

</tr>

<tr>

<tdalign=“center”>

AP

</td>

<tdalign=“center”>

Appreciable

</td>

<tdalign=“center”>

9-11

</td>

</tr>

<tr>

<tdalign=“center”>

AC

</td>

<tdalign=“center”>

Accelerating

</td>

<tdalign=“center”>

12-13

</td>

</tr>

<tr>

<tdalign=“center”>

OS

</td>

<tdalign=“center”>

Outstanding

</td>

<tdalign=“center”>

14-15

</td>

</tr>

</table>

</td>

</tr>

<tr>

<tdbgcolor=“White”colspan=“3”>&nbsp;</td>

</tr>

</table>

</td>

</tr>

</table>

</form>

</body>

</html>

UseCase:Reportbyclass.

RequirementsSpecificationReference:R11

PrototypeReference:P10

Prerequisite:Theuserhastobeloggedinandmusthavetherolewhichhastheprivilegetoaccessreportbyclassfunctionality.

Thisusecaseneedstobeimplementedaspertherequirementsspecificationreferenceabove.TheUIneedstobeaspertheprototypereferenceabove.NowthatwehavecompleteclarityonusecaserequirementsandUIwewillnowproceedtoimplementthisusecase.

Inordertoimplementthisusecase,weneedtofollowthearchitectureandleveragetheframework.Toachievethiswewillfirstcomeupwithdetaileddesignandthencodeit.

Theprerequisiteforthisusecaseisthattheusermustloggedinandbelongtotherolewhichhasaccesstoreports.Whentheuserclicksonreportsbyclasslinkeitherondashboardorviathemenu,thefollowingflowistriggered.

Theuserclicksthereportbyclasslink

Thehrefforthislinkis

BisControllerServlet?ParameterActionCommand=GetReportByClass

TheControllerServletisinvokedontheserver

IntheservicemethodtheactioncommandparametervalueisreadwhichisGetReportByClass

TheexecutemethodforthecommandprocessorpertainingtoGetReportByClassisinvoked

Thebusinesslogicpertainingtothiscommandprocessorisexecutedandaviewisreturned

Theresponseisreturnedtothebrowserwiththisview

Theuserseesthereportbyclasspage

Theusersselectsthereportcriteriaandclicksgeneratereport.

ThecommandprocessorclasspertainingtoGetReportByClasscommandisGetReportByClassCP.TheviewpertainingtostudentdetailpageisReportByClass.jsp.Now,letsseethesequenceofmethodcallsoncetheexecutemethodofGetReportByClassCPiscalled.Belowisthesequencediagramfromthisusecase.

Theexecutemethodofgetreportbyclasscommandprocessoriscalledfromthecontrollerservlet.Theexecutemethodcallsprocessgetreportbyclassmethodofthereportbyclassserviceclass.Thisprocessmethodreadsthereportcriteriai.e.thesectionandthegradefromthehttprequestparametersendfromthejsppage.Thentheprocessmethodinvokestheprivatemethodpopulatereportbyclassdata.Inpopulatereportbyclassdatamethod,aselectqueryisexecutedatthedatabaseforthegivencriteria(withawhereclauseforgradeandsection).Thismayreturnoneormorerecords.Theserecordsarecapturedin‘n’numberofinstancesofStudentDetailsBean.AlltheseinstancesarethenaddedtoanArrayList.Thisarraylististhenaddedtothesession.Thejspconsumesthisarraylist,itgetsalltheinstancesanddisplaysthemasarecordeachonthereportsresultsregionofthepage.

Atthisstagewehavetherequirements,prototype,architecture,frameworkanddetaileddesignforthegetreportbyclassusecaseintheformofsequenceandclassdiagrams.Thenextandthemostinterestingpartiscodingthisusecase.Intheearlierchapter,wehavealreadycreatedthedatabasetablesandaddedsometestdatathere.Letsidentifyalltheartifactsfirst.Forthisusecaseweneedthefollowingfiles.

ReportByClass.jsp

GetReportByClassCP.java

ReportByClassService.java

ReportByClassBean.java

GetReportByClassCP.java

Pleasereferchapter14(TheBIS-SMSProjectComponents)forclassdiagramoncebeforeweproceedwiththisclass.ThisclassimplementsBisCommandinterfacewhichhasonlyonemethodexecute.ThisclassextendsBisCPwhichhasfewvariables.Wehavetoimplementexecutemethodinthisclassforgetstudentdetailsusecase.Letslookintotheactualsourcecodeforthisclassnow.

packagecom.bis.cp;

importcom.bis.session.reports.ReportByClassService;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importorg.apache.log4j.Logger;

publicclassGetReportByClassCPextendsBisCPimplementsBisCommand{

staticLoggerlogger=Logger.getLogger(GetReportByClassCP.class);

publicGetReportByClassCP(){

super();

}

publicStringexecute(HttpServletRequestrequest,HttpServletResponseresponse){

ReportByClassServicereportByClassService=newReportByClassService();

try{

reportByClassService.processGetReportByClass(request);strNextNavigation=“ReportByClass”;

}catch(Exceptionexcep){

logger.error(excep.getMessage());

strNextNavigation=“Error”;//Thenextnavigationpageuponfailedprocessing.

}

returnstrNextNavigation;

}

}

TheexecutemethodofGetReportByClassCPClass.

Theexecutemethodiscalledfromthecontrollerservlet.Thisisthejoboftheframework.TheframeworkgetsthecommandfromUIandbasedonthecommandloadsandexecutesaspecificcommandprocessorexploitingthepolymorphicfeatureofjava.Inthiscase,thecommandfromUIis“GetReportByClass”.Withintheservicemethodofcontrollerservlet,theGetReportByClassCPclassisloadedandinstantiatedandtheexecutemethodisinvoked.

Theexecutemethodperformsthefollowingactions:

CreatesaninstanceofReportByClassServiceandinvokesprocessGetReportByClassmethod.

SetsthenextnavigationtoReportByClass.

ReportByClassService.java

NowletsseetheReportByClassServiceclasssourcecode.

packagecom.bis.session.reports;

importcom.bis.beans.reports.ReportByClassBean;

importcom.bis.db.DatabaseService;

importcom.bis.session.BisService;

importjava.sql.Connection;

importjava.sql.ResultSet;

importjava.sql.SQLException;

importjava.sql.Statement;

importjava.util.ArrayList;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpSession;

importorg.apache.log4j.Logger;

publicclassReportByClassServiceimplementsBisService{

staticLoggerlogger=Logger.getLogger(ReportByClassService.class);

publicReportByClassService(){

super();

}

publicvoidprocessGetReportByClass(HttpServletRequestrequest){

StringstrClass;

StringstrSection;

strClass=request.getParameter(“selClass”);

strSection=request.getParameter(“selSection”);

if(strClass!=null&&strSection!=null){

ArrayListreportsBeansList=pupulateReportsByClassData(strClass,strSection);

HttpSessionsession=request.getSession();

session.setAttribute(“reportsBeansList”,reportsBeansList);

session.setAttribute(“grade”,strClass);

session.setAttribute(“section”,strSection);

}

else{

logger.error(“Section/Classisnull”);

}

}

privateArrayListpupulateReportsByClassData(StringstrClass,StringstrSection){

Connectionconnection=null;

Statementstatement=null;

ResultSetresultSet=null;

StringstrFirstName=””;

StringstrMiddleName=””;

StringstrLastName=””;

StringstrFullName=””;

StringstrStudentId=””;

StringstrGender=””;

StringstrBusId=””;

ReportByClassBeanreportByClassBean;

ArrayList<ReportByClassBean>reportsBeansList=newArrayList<ReportByClassBean>();

StringBuffersbQuery=newStringBuffer(“SELECTFIRST_NAME,MIDDLE_NAME,LAST_NAME,STUDENT_ID,GENDER_CODE,BUS_IDFROMSTUDENT_DETAILSWHEREGRADE=’”);

sbQuery.append(strClass);

sbQuery.append(”’ANDSECTION=’”);

sbQuery.append(strSection);

sbQuery.append(”’”);

DatabaseServicedatabaseService=newDatabaseService();

connection=databaseService.getDBConnection();

try{

statement=connection.createStatement();

resultSet=statement.executeQuery(sbQuery.toString());

while(resultSet.next()){

//Preparefullname

strFirstName=resultSet.getString(“FIRST_NAME”);

strMiddleName=resultSet.getString(“MIDDLE_NAME”);

strLastName=resultSet.getString(“LAST_NAME”);

if(strFirstName!=null){

strFullName=strFirstName;

}

if(strMiddleName!=null){

strFullName=strFullName+””+strMiddleName;

}

if(strLastName!=null){

strFullName=strFullName+””+strLastName;

}

//preparegenderfromcode

strGender=resultSet.getString(“GENDER_CODE”);

if(strGender!=null){

if(strGender.equalsIgnoreCase(“F”)){

strGender=“Female”;

}

else{

strGender=“Male”;

}

}

else{

strGender=””;

}

//studentidandbusid

strStudentId=resultSet.getString(“STUDENT_ID”);

strBusId=resultSet.getString(“BUS_ID”);

//Nowwearereadywithonecompelterecord.

reportByClassBean=newReportByClassBean();

reportByClassBean.setStudentName(strFullName);

reportByClassBean.setStudentId(strStudentId);

reportByClassBean.setGender(strGender);

reportByClassBean.setStudentId(strStudentId);

reportByClassBean.setBusId(strBusId);

reportsBeansList.add(reportByClassBean);

}

}catch(SQLExceptionsqle){

logger.error(sqle.getMessage());

}finally{

databaseService.closeDBResouces(statement,resultSet);

databaseService.releaseDBConnection();//Releasingdatabaseconnection.

}

returnreportsBeansList;

}

publicStringgetServiceName(){

returnnull;

}

}

TheprocessGetReportByClassmethodperformsthefollowingtasks:

Getstherequestparametervalueforselectedclassandsection.

CallstheprivatemethodpopulateReportsByClassDatamethodtopopulatethedatafromdatabaseintoanarraylistofReportByClassBeaninstances.

AddsthisarraylistofReportByClassBeaninstancestothesessionwhichisconsumedbythejsp.

Addstheselectedclassandgradetosessionwhichistobedisplayedasselectedreportcriteria.

ThepupulateReportsByClassDatamethodperformsthefollowingtasks:

Cooksupthedynamicselectqueryforthegivenclassandsection.

GetsthedatabaseconnectionfromDatabaseServiceclass.

Createsthestatementandexecutesthequery.

PopulatestheReportByClassBeaninstancefromtheResultSetforeachrecord.

EachReportByClassBeaninstancewhichnowrepresentsarecordfromdatabasequeryisaddedtothearraylist.ThisarraylistnowholdsalltherecordsasnumberofinstancesofReportByClassBean.

Fore.g.saytheuserselectedclassVIandsectionA.Thedynamicquerywilladdthesetwoconditionsinthewhereclauseforsectionandclass.Supposesay,thequeryreturned11recordsforthiscriteria.AninstanceofReportByClassBeaniscreatedandpopulatedwithsetters.ThissingleinstanceofReportByClassBeanholdsdataforonerecord.Similarly11suchinstancesofReportByClassBeanarecreatedandineachdatapertainingtoeachrecordfromResultSetisadded.Thisarraylistnowholds11instancesofReportByClassBean.Thearraylististhanaddedtothesession.Onthejspside,thearraylistisfetchedfromthesession.AndfromthearraylisteachinstanceofReportByClassBeanisfetchedandthefieldsfromitaredisplayedasonerow.Hencetheresultantreportjsppagewilldisplay11records.

ReportByClassBean.java

TheReportByClassBeanclassisjustasimplejavabeanwithprivatefieldswiththeirgettersandsetters.Pleaserefertheclassdiagramandbelowsourcecodeforunderstandingthisclass.

packagecom.bis.beans.reports;

importcom.bis.beans.BisBean;

publicclassReportByClassBeanextendsBisBean{

publicReportByClassBean(){

super();

}

privatejava.lang.StringstudentName;

privatejava.lang.StringstudentId;

privatejava.lang.Stringgender;

privatejava.lang.StringbusId;

publicvoidsetStudentName(StringstudentName){

this.studentName=studentName;

}

publicStringgetStudentName(){

returnstudentName;

}

publicvoidsetStudentId(StringstudentId){

this.studentId=studentId;

}

publicStringgetStudentId(){

returnstudentId;

}

publicvoidsetGender(Stringgender){

this.gender=gender;

}

publicStringgetGender(){

returngender;

}

publicvoidsetBusId(StringbusId){

this.busId=busId;

}

publicStringgetBusId(){

returnbusId;

}

}

ReportByClass.jsp

ThisjspisdynamicallyincludedinBisHome.jspasaresultforgetreportbyclassusecaseinvocationthroughuserinteractionwiththeUI.Fortheinitialrequesttothispageweonlyneedtodisplaythereportscriteria.ThisisachievedbycheckingnullforthearraylistofReportyByClassBean.Hence,forthefirstrequesttothispageonlythecriteriaisdisplayed.Oncetheuserselectsthecriteriaandhitsgeneratereport,theresultantreportisdisplayedwith“n”numberofrecordsasdescribedintheexampleabove.

TillnowwehaveseenthatthecommandforreportbyclassgoesformUIasaresultofuserinteraction.Thenthecontrollerservletcallsgetreportbyclasscommandprocessorandthenthereportbyclassserviceisleveraged.Finally,wegettheresultspackagedasanarraylistofinstancesofReportByClassBean.Thisarraylistwiththennumberofbeaninstancesisnowavailableinthesession.IntheReportByClass.jspfilewefetchthisarraylistofbeaninstancesfromthesession.Andfromeachbeanwefetchalltheinformationrelatedtostudentdetailsusingthegetters.Thestaticpartofthejspremainsthesameasthatoftheprototypepage.Onlythedynamicpartisaddedusingthearraylistofthebeansfromthesession.Hence,theenduserseestheviewforagivenreportcriteriawithallthestudentrecords.

HereisthesourcecodefortheReportByClass.jspfile.

<%@pageimport=“com.bis.beans.reports.ReportByClassBean”%>

<%@pageimport=“java.util.ArrayList”%>

<%@pageimport=“java.util.Iterator”%>

<%

ReportByClassBeanreportByClassBean;

IteratorrecItr=null;

if(session!=null){

ArrayListreportsBeansList=(ArrayList)session.getAttribute(“reportsBeansList”);

if(reportsBeansList!=null){

recItr=reportsBeansList.iterator();

}

}

%>

<formid=“frmReportByCls”name=“frmReportByCls”method=“POST”action=“BisControllerServlet”>

<inputtype=“hidden”name=“ParameterActionCommand”value=“GetReportByClass”></input>

<tableborder=“0”cellpadding=“0”cellspacing=“0”width=“100%”height=“99%”>

<tr>

<tdwidht=”*”align=“center”valign=“top”>

<tableborder=“0”cellpadding=“10”cellspacing=“0”width=“100%”>

<tr><td>&nbsp;</td></tr>

<tr>

<tdbgcolor=“White”align=“center”id=“clred”colspan=“3”>

Class:

<selectname=“selClass”id=“selClass”>

<optionselected=“true”value=“I”>

I

</option>

<optionvalue=“II”>

II

</option>

<optionvalue=“III”>

III

</option>

<optionvalue=“IV”>

IV

</option>

<optionvalue=“V”>

V

</option>

<optionvalue=“VI”>

VI

</option>

<optionvalue=“VII”>

VII

</option>

<optionvalue=“VIII”>

VIII

</option>

<optionvalue=“IX”>

IX

</option>

<optionvalue=“X”>

X

</option>

</select>

&nbsp;&nbsp;

Section:

<selectname=“selSection”id=“selSection”>

<optionselected=“true”value=“A”>

A

</option>

<optionvalue=“B”>

B

</option>

<optionvalue=“C”>

C

</option>

<optionvalue=“D”>

D

</option>

<optionvalue=“E”>

E

</option>

<optionvalue=“F”>

F

</option>

<optionvalue=“G”>

G

</option>

</select>

&nbsp;&nbsp;

<inputtype=“button”value=“GenerateReport”name=“btnGenRepByCls”id=“btnGenRepByCls”onclick=“generateRptByCls()”>

</td>

</tr>

<tr><td>&nbsp;</td></tr>

<trvalign=“middle”>

<tdalign=“center”>

<tableborder=“1”cellpadding=“4”cellspacing=“0”width=“80%”bgcolor=“White”>

<trid=“clred”>

<tdcolspan=“12”align=“center”>

&nbsp;&nbsp;Report:ClassWise

&nbsp;&nbsp;|&nbsp;&nbsp;

Class:

<%

StringstrGrade=(String)session.getAttribute(“grade”);

if(strGrade!=null){

out.print(strGrade);

}

else{

out.print(“None”);

}

%>

&nbsp;&nbsp;|&nbsp;&nbsp;

Section:

<%

StringstrSection=(String)session.getAttribute(“section”);

if(strSection!=null){

out.print(strSection);

}

else{

out.print(“None”);

}

%>

</td>

</tr>

<trid=“trbgred”>

<tdalign=“center”width=”*”>

Name

</td>

<tdalign=“center”width=“20%”>

StudentId

</td>

<tdalign=“center”width=“20%”>

Gender

</td>

<tdalign=“center”width=“20%”>

BusId

</td>

</tr>

<%

if(recItr!=null){

while(recItr.hasNext()){

reportByClassBean=(ReportByClassBean)recItr.next();

%>

<tr>

<tdalign=“center”>

<%=reportByClassBean.getStudentName()%>

</td>

<tdalign=“center”>

<%=reportByClassBean.getStudentId()%>

</td>

<tdalign=“center”>

<%=reportByClassBean.getGender()%>

</td>

<tdalign=“center”>

<%=reportByClassBean.getBusId()%>

</td>

</tr>

<%}}%>

</table>

</td>

</tr>

</table>

</td>

</tr>

</table>

</form>

Forthisusecasepleasestudythedynamicpartofthejspcode.Wefetchedthearraylistfromthesession.Fromarraylistwegottheiterator.Weusedthisiteratortodynamicallydisplayalltherecords(witheachandeveryindividualfields)inatabularformat.

Thisconcludesthegetreportbyclassusecaseimplementationfromendtoend.Wecomposedtherequirementspecifications,webuilttheprototype,wefollowedthearchitectureforthesolution,weleveragedtheframework,wedevelopedthevariousjavaclasses,weusedthecommoncomponentslikeDatabaseService.java,BISStyle.cssetcandwebuilttheviewwiththejsppage.

UseCase:AddStudent.

RequirementsSpecificationReference:R10

PrototypeReference:P9

Prerequisite:Theuserhastobeloggedinandmusthavetherolewhichhastheprivilegetoaddanewstudent.

Thisusecaseneedstobeimplementedaspertherequirementsspecificationreferenceabove.TheUIneedstobeaspertheprototypereferenceabove.NowthatwehavecompleteclarityonusecaserequirementsandUIwewillnowproceedtoimplementthisusecase.

Inordertoimplementthisusecase,weneedtofollowthearchitectureandleveragetheframework.Toachievethiswewillfirstcomeupwithdetaileddesignandthencodeit.

Theprerequisiteforthisusecaseisthattheuserhastobeloggedinandmusthavetherolewhichhastheprivilegetoaddanewstudent.Whentheuserclicksonaddstudentlink

eitherondashboardorviathemenu,thefollowingflowistriggered.

Theuserclickstheaddstudentlink

Thehrefforthislinkis

BisControllerServlet?ParameterActionCommand=AddStudent

TheControllerServletisinvokedontheserver

IntheservicemethodtheactioncommandparametervalueisreadwhichisAddStudent

TheexecutemethodforthecommandprocessorpertainingtoAddStudentisinvoked

Thebusinesslogicpertainingtothiscommandprocessorisexecutedandaconfirmationmessageisreturned.

ThecommandprocessorclasspertainingtoAddStudentcommandisAddStudentCP.TheviewpertainingtostudentdetailpageisAddStudent.jsp.Now,letsseethesequenceofmethodcallsoncetheexecutemethodofAddStudentCPiscalled.Belowisthesequencediagramfromthisusecase.

ThecontrollerservletinvokestheexecutemethodoftheAddStudentcommandprocessor.Thefirstthingtheexecutemethoddoesisthatitcheckswhetherthisisarequestforblankformorisafilledformsubmission.Thisisdoneviaarequestparameterwhichissendbytheaddstudentviewasahiddenvariable.Ifitisarequestforblankformtheexecutemethodreturnstheview.Ifitisaformsubmission,theexecutemethodinvokesprocessaddstudentmethodintheAddStudentServiceclass.

Theprocessaddstudentmethodcallstheprivatemethodprepareaddstudentmodel.TheprepareaddstudentmodelmethodreadsallthehttprequestparameterssentfromthejspformandpopulatestheStudentDetailsBean.Now,wehaveallthedatafromtheformintheformofabeaninstance.Theprocessmethodgetsthedatabaseconnectionandexplicitlyturnsofftheautocommitmode.Theprocessmethodtheninvokesthreeprivatemethods,eachofthesemethodsinsertonerecordtorespectivetables.ThesethreemethodsreturnthestatusofinsertionasaBooleanvalue.AllthethreeBooleanvaluesarechecked,ifallofthemaretruethanthetransactioniscommittedelsethetransactionisrolledback.Finally,theaddstudentviewisreturnedtotheuser.

Atthisstagewehavetherequirements,prototype,architecture,frameworkanddetaileddesignfortheaddstudentusecaseintheformofsequenceandclassdiagrams.Thenextandthemostinterestingpartiscodingthisusecase.Intheearlierchapter,wehavealreadycreatedthedatabasetablesandaddedsometestdatathere.Letsidentifyalltheartifactsfirst.Forthisusecaseweneedthefollowingfilesalongwiththecommons.

AddStudent.jsp

AddStudentCP.java

StudentDetailsBean.java

AddStudentCP.java

Pleasereferchapter14(TheBIS-SMSProjectComponents)forclassdiagramoncebeforeweproceedwiththisclass.ThisclassimplementsBisCommandinterfacewhichhasonlyonemethodexecute.ThisclassextendsBisCPwhichhasfewvariables.Wehavetoimplementexecutemethodinthisclassforgetstudentdetailsusecase.Letslookintotheactualsourcecodeforthisclassnow.

packagecom.bis.cp;

importcom.bis.session.AddStudentService;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importorg.apache.log4j.Logger;

publicclassAddStudentCPextendsBisCPimplementsBisCommand{

staticLoggerlogger=Logger.getLogger(AddStudentCP.class);

publicAddStudentCP(){

uper();

}

StringstrAddStdFrmSubmitted=“No”;//Defaultingaddstudentformsubmittedhiddenvaluetofalse.

publicStringexecute(HttpServletRequestrequest,HttpServletResponseresponse){

strAddStdFrmSubmitted=request.getParameter(“paramAddStdFrmSubmitted”);

try{

if(strAddStdFrmSubmitted!=null&&strAddStdFrmSubmitted.equalsIgnoreCase(“Yes”)){

AddStudentServiceaddStudentService=newAddStudentService();

addStudentService.processAddStudent(request);

}

strNextNavigation=“AddStudent”;//Thenextnavigationpageuponsuccessfulprocessing.

}catch(Exceptionexcep){

logger.error(excep.getMessage());

strNextNavigation=“Error”;//Thenextnavigationpageuponfailedprocessing.

}

returnstrNextNavigation;

}

}

TheexecutemethodofAdddentCPClass.

Theexecutemethodiscalledfromthecontrollerservlet.Thisisthejoboftheframework.TheframeworkgetsthecommandfromUIandbasedonthecommandloadsandexecutesaspecificcommandprocessorexploitingthepolymorphicfeatureofjava.Inthiscase,thecommandfromUIis“AddStudent”.Withintheservicemethodofcontrollerservlet,theAddStudentCPclassisloadedandinstantiatedandtheexecutemethodisinvoked.

Theexecutemethodperformsthefollowingtasks:

Getsthenewstudentformsubmittedflagfromtherequestparameter.ThisisYesincasetheuserhassubmittedtheaddnewstudentformusingtheAddStudent.jsp.ThisisNoincasetheuserhasrequestedtheaddnewstudentblankform.Thatis,theinitialloadoftheaddstudentpageinordertofillitandsubmitit.

ChecksthevalueforparamAddStdFrmSubmittedparameter.

Ifyes,createsaninstanceofAddStudentServiceandcallsprocessAddStudentmethod.Thismethodorchestratestheinsertionofnewrecordsinthedatabaseforthenewstudent.Andfinally,setsthenextnavigationview.

Ifno,directlysetsthenextnavigationtoAddStudent.Thisloadstheblankformonthebrowserinordertosubmitanewstudent.Theuserseestheaddstudentformpage.

AddStudentService.java

Now,letusseethesourcecodeofAddStudentService.javaclass.

packagecom.bis.session;

importcom.bis.beans.StudentDetailsBean;

importcom.bis.db.DatabaseService;

importcom.bis.utility.BisUtility;

importjava.sql.Connection;

importjava.sql.PreparedStatement;

importjava.sql.SQLException;

importjava.text.ParseException;

importjava.text.SimpleDateFormat;

importjavax.servlet.http.HttpServletRequest;

importorg.apache.log4j.Logger;

publicclassAddStudentServiceimplementsBisService{

staticLoggerlogger=Logger.getLogger(AddStudentService.class);

publicAddStudentService(){

super();

}

publicvoidprocessAddStudent(HttpServletRequestrequest){

booleanisStudentInfoInsertedToSD=false;

booleanisStudentInfoInsertedToSA=false;

booleanisParentsInfoInserted=false;

StudentDetailsBeanstudentDetailsBean=null;

Connectionconnection=null;

studentDetailsBean=prepareAddStudentModel(request);

connection=DatabaseService.getDBConnection();

try{

connection.setAutoCommit(false);

isStudentInfoInsertedToSD=insertNewStudentToSD(studentDetailsBean,connection);

isStudentInfoInsertedToSA=insertNewStudentToSA(studentDetailsBean,connection);

isParentsInfoInserted=insertNewStudentParentsInfoToDb(studentDetailsBean,connection);

if(isStudentInfoInsertedToSD&&isParentsInfoInserted&&isStudentInfoInsertedToSA){

connection.commit();

BisUtility.sendMail(“Newstudent”+studentDetailsBean.getFirstName()+””+studentDetailsBean.getLastName()+”isadded.”,“Thenewstudentwiththeid:“+studentDetailsBean.getStudentId()+”isadded.”);

}

else{

connection.rollback();

logger.error(“Newstudentinsertiontodatabasefailed.”);

}

}catch(SQLExceptionsqle){

logger.error(sqle.getMessage());

}

finally{

DatabaseService.releaseDBConnection();//Releasingdatabaseconnection.

}

}

privateStudentDetailsBeanprepareAddStudentModel(HttpServletRequestrequest){

StudentDetailsBeanstudentDetailsBean=newStudentDetailsBean();

studentDetailsBean.setFirstName(request.getParameter(“txtFirstName”));studentDetailsBean.setMiddleName(request.getParameter(“txtMiddleName”));

studentDetailsBean.setLastName(request.getParameter(“txtLastName”));

studentDetailsBean.setFather(request.getParameter(“txtFatherName”));

studentDetailsBean.setFatherMobile(request.getParameter(“txtFatMob”));

studentDetailsBean.setMother(request.getParameter(“txtMotherName”));

studentDetailsBean.setMotherMobile(request.getParameter(“txtMotMob”));

studentDetailsBean.setAddress(request.getParameter(“taAddress”));

studentDetailsBean.setGender(request.getParameter(“radSex”));

studentDetailsBean.setDob(request.getParameter(“datDob”));

studentDetailsBean.setGrade(request.getParameter(“selGrade”));

studentDetailsBean.setSection(request.getParameter(“selSection”));

studentDetailsBean.setWeight(request.getParameter(“numWeight”));

studentDetailsBean.setHeight(request.getParameter(“txtHeight”));

studentDetailsBean.setSiblings(request.getParameter(“txtSiblings”));

studentDetailsBean.setBloodGroup(request.getParameter(“selBldGrp”));

studentDetailsBean.setBusId(request.getParameter(“selBusId”));

StringstrDob=studentDetailsBean.getDob();

StringBuffersbStudentId=BisUtility.generateStudentId(studentDetailsBean.getFirstName(),studentDetailsBean.getLastName(),studentDetailsBean.getMother(),studentDetailsBean.getFather(),strDob);

studentDetailsBean.setStudentId(sbStudentId.toString());

returnstudentDetailsBean;

}

privatebooleaninsertNewStudentToSD(StudentDetailsBeanstudentDetailsBean,Connectionconnection){

booleanisStudentInfoInserted=false;

intinsertCount=0;

java.sql.DatedatDob=null;

PreparedStatementpreparedStatement=null;

DatabaseServicedatabaseService=newDatabaseService();

SimpleDateFormatsdFormat=newSimpleDateFormat(“yyyy-MM-dd”);

StringstrInsertQuery=“INSERTINTOSTUDENT_DETAILS(STUDENT_ID,ACTIVE_FLAG,FIRST_NAME,MIDDLE_NAME,LAST_NAME,GENDER_CODE,BIRTH_DATE,GRADE,SECTION,HEIGHT,WEIGHT,BLOOD_GROUP,SIBLINGS_STUDENT_IDS,BUS_ID)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)”;

try{

java.util.DateparsedDate=sdFormat.parse(studentDetailsBean.getDob());

datDob=newjava.sql.Date(parsedDate.getTime());

preparedStatement=connection.prepareStatement(strInsertQuery);

preparedStatement.setString(1,studentDetailsBean.getStudentId());

preparedStatement.setString(2,“Y”);

preparedStatement.setString(3,studentDetailsBean.getFirstName());

preparedStatement.setString(4,studentDetailsBean.getMiddleName());

preparedStatement.setString(5,studentDetailsBean.getLastName());

preparedStatement.setString(6,studentDetailsBean.getGender());

preparedStatement.setDate(7,datDob);

preparedStatement.setString(8,studentDetailsBean.getGrade());

preparedStatement.setString(9,studentDetailsBean.getSection());

preparedStatement.setString(10,studentDetailsBean.getHeight());

preparedStatement.setString(11,studentDetailsBean.getWeight());

preparedStatement.setString(12,studentDetailsBean.getBloodGroup());

preparedStatement.setString(13,studentDetailsBean.getSiblings());

preparedStatement.setString(14,studentDetailsBean.getBusId());

insertCount=preparedStatement.executeUpdate();

if(insertCount==1){

isStudentInfoInserted=true;

}

else{

logger.error(“FailedtoinsertnewstudentrecordinStudent_Detailstable”);

}

}catch(SQLExceptionsqle){

isStudentInfoInserted=false;

logger.error(sqle.getMessage());

}catch(ParseExceptionpe){

logger.error(pe.getMessage());

}

finally{

databaseService.closeDBResouces(preparedStatement,null);

}

returnisStudentInfoInserted;

}

//InsertstworowstoStudent_Attendancetablewithzeroattendanceforeachsemester.Provisioningforlaterupdate.

privatebooleaninsertNewStudentToSA(StudentDetailsBeanstudentDetailsBean,Connectionconnection){

booleanisStudentInfoInsertedToSA=false;

intinsertCountSem1=0;

intinsertCountSem2=0;

PreparedStatementpreparedStatement=null;

DatabaseServicedatabaseService=newDatabaseService();

StringstrInsertQuery=“INSERTINTOSTUDENT_ATTENDANCE(STUDENT_ID,ATTENDANCE,SEMESTER)VALUES(?,?,?)”;

try{

preparedStatement=connection.prepareStatement(strInsertQuery);

preparedStatement.setString(1,studentDetailsBean.getStudentId());

preparedStatement.setInt(2,0);

preparedStatement.setString(3,“1”);

insertCountSem1=preparedStatement.executeUpdate();

preparedStatement.setString(3,“2”);

insertCountSem2=preparedStatement.executeUpdate();

if(insertCountSem1==1&&insertCountSem2==1){

isStudentInfoInsertedToSA=true;

}

else{

logger.error(“FailedtoinsertnewstudentrecordinStudent_Attendancetable”);

}

}catch(SQLExceptionsqle){

isStudentInfoInsertedToSA=false;

logger.error(sqle.getMessage());

}

finally{

databaseService.closeDBResouces(preparedStatement,null);

}

returnisStudentInfoInsertedToSA;

}

privatebooleaninsertNewStudentParentsInfoToDb(StudentDetailsBeanstudentDetailsBean,Connectionconnection){

booleanisParentsInfoInserted=false;

PreparedStatementpreparedStatement=null;

DatabaseServicedatabaseService=newDatabaseService();

intinsertCount=0;

StringstrInsertQuery=“INSERTINTOPARENT_DETAILS(FATHER_NAME,MOTHER_NAME,FATHER_MOBILE,MOTHER_MOBILE,ADDRESS,FATHER_QUALIFICATION,MOTHER_QUALIFICATION,

ANNUAL_INCOME,STUDENT_ID)VALUES(?,?,?,?,?,?,?,?,?)”;

try{

preparedStatement=connection.prepareStatement(strInsertQuery);

preparedStatement.setString(1,studentDetailsBean.getFather());

preparedStatement.setString(2,studentDetailsBean.getMother());

preparedStatement.setString(3,studentDetailsBean.getFatherMobile());

preparedStatement.setString(4,studentDetailsBean.getMotherMobile());

preparedStatement.setString(5,studentDetailsBean.getAddress());

preparedStatement.setString(6,studentDetailsBean.getFatherQual());

preparedStatement.setString(7,studentDetailsBean.getMotherQual());

preparedStatement.setString(8,studentDetailsBean.getAnnualIncome());

preparedStatement.setString(9,studentDetailsBean.getStudentId());

insertCount=preparedStatement.executeUpdate();

if(insertCount==1){

isParentsInfoInserted=true;

}

else{

logger.error(“Failedtoinsertnewstudentparent’srecordinParents_Detailstable”);

}

}catch(SQLExceptionsqle){

isParentsInfoInserted=false;

logger.error(sqle.getMessage());

}

finally{

databaseService.closeDBResouces(preparedStatement,null);

}

returnisParentsInfoInserted;

}

publicStringgetServiceName(){

returnthis.getClass().getName();

}

}

TheprocessAddStudentmethodperformsthefollowingtasks:

CreatesaninstanceofStudentDetailsBeanandcallsprepareAddStudentModelmethodtopopulatethedatasentviathehtmlformintothisbeaninstance.Thisinstancenowholdstheclientsidevalidateddatasentbytheuserbysubmittingadd

studentform.

LeveragesDatabaseServiceclasstogetdatabaseconnection.

Setsautocommitforthedatabaseconnectiontofalse.Inthiscasewehavetoexplicitlycommitorrollbackthedatabaseinsertionoperations.Wedidthisinordertomanuallycontrolthedatabasetransaction.Forthisusecasewehavetoinsertarecordinthreetables.Thishastobeaneitherallornoneoperation.Therecordsforanewstudentmustgoinallthesethreetables,incaseofsuccess,wewillcommitit.Iftheinsertionfailsinoneormoretables,weperformtherollbackwhichensuresthatnoneofthedetailsaboutthestudentareenteredtoanyofthetables.Thissavesusfrominconsistenciesofdataforagivenstudent.

Initializesthreebooleanvariablestocapturestatusofinsertiontoeachtable.

Forcreatinganewstudent,weneedtoinsertonerecordintoeachofthefollowingtables:Student_details,Parent_detailsandStudent_attendance.Thisisachievedviacallstothreeprivatemethodsinthesameclass.Allthesemethodsreturnabooleanvaluewhichisnothingbutthestatusoftheoperation.Eachmethodreturntrueiftheinsertionsucceedsandfalseiftheinsertionfails.

Aftercallingallthethreemethodsthebooleanreturnedstatusarechecked,ifallthetreereturnedvaluesaretrue,thetransactioniscommittedandanemailissentusingsendEmailmethodofBisUtilityclass.

Ifoneormorereturnedvaluesarefalse,thetransactionisrolledback.Thisguaranteesthattherecordsareinsertedeitherinallthethreetablesornone.

TheprepareAddStudentModelmethodperformsthefollowingtasks:

Readsthevaluesofalltheformelementssentfromthejsppage.AlltheseparametersarereadfromtherequestobjectandthevaluesarepopulatedtotheStudentDetailsBeaninstanceusingsettermethods.

CallsthegenerateStudentIdmethodinBisUtilityclassinordertogeneratestudentidfromthevaluessubmittedbytheuserforagivenstudent.

Callsthesettermethodofstudentdetailsbeaninstancetosetthisgeneratedstudentid.

Andfinally,returnsthispopulatedinstanceofstudentdetailsbean.

TheinsertNewStudentToSDmethodperformsthefollowingtasks:

Cooksupthedynamicinsertquerywithplaceholdersforaddinganewrecordtostudentdetailstable.

GetsthedatabaseconnectionfromDatabaseServiceclass.

Getsthepreparedstatementfromtheconnectionforthegivenquery.

UsessetXXXmethodsofpreparedstatementtosetthevaluesfetchedfromthestudentdetailsbeaninstance.

Callsexecuteupdatemethodtoinsertarecordtothedatabasetablestudentdetails.

Thestatusiscapturedinabooleanvariableandisreturnedtothecallingmethod.

Performstheclosureofdatabaseresourcesinthefinallyblock.

TheinsertNewStudentToSAmethodperformsthefollowingtasks:

Cooksupthedynamicinsertquerywithplaceholdersforaddinganewrecordtostudentattendancetable.

GetsthedatabaseconnectionfromDatabaseServiceclass.

Getsthepreparedstatementfromtheconnectionforthegivenquery.

UsessetXXXmethodsofpreparedstatementtosetthevaluesfetchedfromthestudentdetailsbeaninstance.

Callsexecuteupdatemethodtoinsertarecordtothedatabasetablestudentattendance.

Thestatusiscapturedinabooleanvariableandisreturnedtothecallingmethod.

Inafinallyblock,thedatabaseresourceswhichwereusedareclosed.

TheinsertNewStudentParentsInfoToDbmethodperformsthefollowingtasks:

Cooksupthedynamicinsertquerywithplaceholdersforaddinganewrecordtoparentdetailstable.

GetsthedatabaseconnectionfromDatabaseServiceclass.

Getsthepreparedstatementfromtheconnectionforthegivenquery.

UsessetXXXmethodsofpreparedstatementtosetthevaluesfetchedfromthestudentdetailsbeaninstance.

Callsexecuteupdatemethodtoinsertarecordtothedatabasetableparentdetails.

Thestatusiscapturedinabooleanvariableandisreturnedtothecallingmethod.

Inafinallyblock,thedatabaseresourceswhichwereusedareclosed.

StudentDetailsBean.java

Pleaserefertothegetstudentdetailsusecaseforthedetailsaboutthisbean.

AddStudent.jsp

ThisjspisdynamicallyincludedinBisHome.jspasaresultforaddstudentusecaseinvocationthroughuserinteractionwiththeUI.

TillnowwehaveseenthatthecommandforaddstudentgoesformUIasaresultofuserinteraction.Thenthecontrollerservletcallsaddstudentcommandprocessor.Thecommandprocessorcheckswhetheritisarequestforablankformtosubmitanewstudentoritisanewstudentformsubmission.Fortheformercase,thecommandprocessorrenderstheblankformviaaddstudentjsppage.Andforthelatercase,thecommandprocessorutilizesaddstudentserviceclasstoinsertanewstudenttothedatabase.

Theaddstudentjsppageprovidesallthemandatoryaswellasoptionalfieldsinordertocreateanewstudent.Allthefieldsarevalidatedattheclientsideusingjavascript.

HereisthesourcecodefortheAddStudent.jspfile.

<formid=“frmAddStudent”name=“frmAddStudent”method=“POST”action=“BisControllerServlet”>

<inputtype=“hidden”name=“ParameterActionCommand”value=“AddStudent”></input>

<inputtype=“hidden”name=“paramAddStdFrmSubmitted”id=“paramAddStdFrmSubmitted”value=“No”></input>

<tableborder=“0”cellpadding=“10”cellspacing=“0”width=“100%”>

<tr><tdcolspan=“2”>&nbsp;</td></tr>

<tr>

<tdalign=“center”colspan=“2”id=“whiteBg”>

AddStudent

</td>

</tr>

<tr><tdcolspan=“2”>&nbsp;</td></tr>

<trvalign=“top”>

<tdwidth=“50%”align=“center”>

<tableborder=“1”cellpadding=“5”cellspacing=“0”width=“90%”bgcolor=“White”>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdwidth=“25%”align=“right”id=“clred”>FirstName&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

<inputtype=“text”size=“30”name=“txtFirstName”maxlength=“30”></input>

</td>

</tr>

<tr>

<tdwidth=“25%”align=“right”id=“clred”>MiddleName&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

<inputtype=“text”size=“30”name=“txtMiddleName”maxlength=“30”></input>

</td>

</tr>

<tr>

<tdwidth=“25%”align=“right”id=“clred”>LastName&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

<inputtype=“text”size=“30”name=“txtLastName”maxlength=“30”></input>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdwidth=”*”align=“right”id=“clred”>Gender&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

<inputtype=“radio”name=“radSex”value=“M”>Male</input>

<inputtype=“radio”name=“radSex”value=“F”>Female</input>

</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>Dateofbirth&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

<inputtype=“date”name=“datDob”></input><!—HTML5Element—>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>Grade&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

<selectname=“selGrade”>

<optionvalue=“LKG”>L.K.G</option>

<optionvalue=“UKG”>U.K.G</option>

<optionvalue=“I”>I-First</option>

<optionvalue=“II”>II-Second</option>

<optionvalue=“III”>III-Third</option>

<optionvalue=“IV”>IV-Fourth</option>

<optionvalue=“V”>V-Fifth</option>

<optionvalue=“VI”>VI-Sixth</option>

<optionvalue=“VII”>VII-Seventh</option>

<optionvalue=“VIII”>VIII-Eight</option>

<optionvalue=“IX”>IX-Ninth</option>

<optionvalue=“X”>X-Tenth</option>

</select>

</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>Section&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

<selectname=“selSection”>

<optionvalue=“A”>A</option>

<optionvalue=“B”>B</option>

<optionvalue=“C”>C</option>

<optionvalue=“D”>D</option>

<optionvalue=“E”>E</option>

</select>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;&nbsp;</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>Height&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

<!—HTML5Element—>

<inputtype=“text”name=“txtHeight”></input>

&nbsp;&nbsp;Foot.Inches

</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>Weight&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

<!—HTML5Element—>

<inputtype=“number”min=“6”max=“150”name=“numWeight”></input>

&nbsp;&nbsp;KG

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>BloodGroup&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

<selectname=“selBldGrp”>

<optionvalue=“AP”>A+ve</option>

<optionvalue=“BP”>B+ve</option>

<optionvalue=“ABP”>AB+ve</option>

<optionvalue=“OP”>O+ve</option>

<optionvalue=“AN”>A-ve</option>

<optionvalue=“BN”>B-ve</option>

<optionvalue=“ABN”>AB-ve</option>

<optionvalue=“ON”>O-ve</option>

</select>

</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>Siblings&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

<inputtype=“text”name=“txtSiblings”size=“40”maxlength=“100”></input>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

</table>

</td>

<tdwidth=”*”align=“center”>

<tableborder=“1”cellpadding=“5”cellspacing=“0”width=“90%”bgcolor=“White”>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdwidth=“25%”align=“right”id=“clred”>Father&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

<inputtype=“text”size=“30”name=“txtFatherName”maxlength=“30”></input>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdwidth=“25%”align=“right”id=“clred”>Mobile&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

<inputtype=“text”name=“txtFatMob”maxlength=“20”></input>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdwidth=”*”align=“right”id=“clred”>Mother&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

<inputtype=“text”size=“30”name=“txtMotherName”maxlength=“30”></input>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdalign=“right”id=“clred”>Mobile&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

<inputtype=“text”name=“txtMotMob”maxlength=“20”></input>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<trheight=“130”>

<tdalign=“right”id=“clred”>Address&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

<textareaname=“taAddress”cols=“45”rows=“6”></textarea>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdwidth=“25%”align=“right”id=“clred”>BusNumber&nbsp;&nbsp;</td>

<tdwidth=”*”align=“left”>

<selectname=“selBusId”>

<optionvalue=“01”>01</option>

<optionvalue=“02”>02</option>

<optionvalue=“03”>03</option>

<optionvalue=“04”>04</option>

<optionvalue=“05”>05</option>

<optionvalue=“06”>06</option>

<optionvalue=“07”>07</option>

<optionvalue=“08”>08</option>

<optionvalue=“09”>09</option>

<optionvalue=“10”>10</option>

<optionvalue=“11”>11</option>

<optionvalue=“12”>12</option>

<optionvalue=“13”>13</option>

<optionvalue=“14”>14</option>

<optionvalue=“15”>15</option>

<optionvalue=“16”>16</option>

<optionvalue=“17”>17</option>

<optionvalue=“18”>18</option>

<optionvalue=“19”>19</option>

<optionvalue=“20”>20</option>

<optionvalue=“11”>21</option>

<optionvalue=“22”>22</option>

<optionvalue=“23”>23</option>

<optionvalue=“24”>24</option>

<optionvalue=“25”>25</option>

<optionvalue=“26”>26</option>

<optionvalue=“27”>27</option>

<optionvalue=“28”>28</option>

<optionvalue=“29”>29</option>

<optionvalue=“30”>30</option>

<optionvalue=”-1”>Private</option>

</select>

</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

<tr>

<tdcolspan=“2”>&nbsp;</td>

</tr>

</table>

</td>

</tr>

<tr>

<tdcolspan=“3”>&nbsp;</td>

</tr>

<trvalign=“middle”align=“center”>

<tdcolspan=“3”>

<inputtype=“submit”name=“subAddStd”value=”Submit”id=“submitButton”onclick=“submitAddStdForm()”></input>

</td>

</tr>

<tr>

<tdcolspan=“3”>&nbsp;</td>

</tr>

</table>

</form>

Thisconcludestheaddnewstudentusecaseimplementationfromendtoend.Wecomposedtherequirementspecifications,webuilttheprototype,wefollowedthearchitectureforthesolution,weleveragedtheframework,wedevelopedthevariousjavaclasses,weusedthecommoncomponentslikeDatabaseService.java,BISStyle.cssetcandwebuilttheviewwiththejsppage.

UseCase:ManageStudentAttendance.

RequirementsSpecificationReference:R9

PrototypeReference:P8

Prerequisite:

1.Theuserhastobeloggedinandmusthavetherolewhichhastheprivilegetoupdatetheattendanceofthestudents.

2.Thestudentwhoseattendanceneedstobeupdatedhastobeloadedintocontextfirst.

Thisusecaseneedstobeimplementedaspertherequirementsspecificationreferenceabove.TheUIneedstobeaspertheprototypereferenceabove.NowthatwehavecompleteclarityonusecaserequirementsandUIwewillnowproceedtoimplementthisusecase.

Inordertoimplementthisusecase,weneedtofollowthearchitectureandleveragetheframework.Toachievethiswewillfirstcomeupwithdetaileddesignandthencodeit.

Theprerequisiteforthisusecaseisthattheuserhastobeloggedinandmusthavetherolewhichhastheprivilegetoupdatetheattendanceofthestudents.Andtheotherprerequisiteisthatthestudentwhoseattendanceneedstobeupdatedmustalreadybeexistinginthecontext,forthistheusermusthaveloadedthestudentfollowingtheloadstudentusecase.Whenthestudentisloaded,thestudentidofaparticularstudentisaddedtothesession.

Youcanrefertheloadstudentusecasefordetailsonthis.Letsassumeasofnowthatthestudentidisexistinginthehttpsession.Whentheuserclicksonmanageattendancelinkeitherondashboardorviathemenu,thefollowingflowistriggered.

Theuserclicksthemanageattendancelink

Thehrefforthislinkis

BisControllerServlet?ParameterActionCommand=ManageAttendance

TheControllerServletisinvokedontheserver

IntheservicemethodtheactioncommandparametervalueisreadwhichisManageAttendance

TheexecutemethodforthecommandprocessorpertainingtoManageAttendanceisinvoked

Thebusinesslogicpertainingtothiscommandprocessorisexecutedresultinginanupdateoftheattendanceinthedatabaseforagivenstudentandsemester.

Theviewpertainingtomanageattendanceisreturnedback.

Theuserseestheupdatedattendanceinthemanageattendancepage.

ThecommandprocessorclasspertainingtoManageAttendancecommandisManageAttendanceCP.TheviewpertainingtostudentdetailpageisManageAttendance.jsp.Now,letsseethesequenceofmethodcallsoncetheexecutemethodofManageAttendanceCPiscalled.Belowisthesequencediagramfromthisusecase.

ThecontrollerservletinvokestheexecutemethodoftheManageAttendancecommandprocessor.Fromthehiddenvariableviatherequestparameter,theexecutemethodscheckswhetherthisisaninitialrequestformanageattendancepage.Ifso,itjustreturnstheview.Ifthisrequestturnsouttobeanupdaterequest,theexecutemethodinvokestheupdatestudentattendancemethodinStudentAttendanceServiceclass.Theupdatestudentattendancemethodreadsthestudentidfromthesessionandthesemesterfromtherequestparameter.ThismethodthenleveragesDatabaseServiceclassandupdatestheattendanceintherequireddatabasetable.

Atthisstagewehavetherequirements,prototype,architecture,frameworkanddetaileddesignforthemanageattendanceusecaseintheformofsequenceandclassdiagrams.Thenextandthemostinterestingpartiscodingthisusecase.Intheearlierchapter,wehavealreadycreatedthedatabasetablesandaddedsometestdatathere.Letsidentifyalltheartifactsfirst.Forthisusecaseweneedthefollowingfilesalongwiththecommons.

ManageAttendanceCP.java

StudentAttendanceService.java

StudentAttendanceBean.java

ManageAttendance.jsp

ManageAttendanceCP.java

Pleasereferchapter14(TheBIS-SMSProjectComponents)forclassdiagramoncebeforeweproceedwiththisclass.ThisclassimplementsBisCommandinterfacewhichhasonlyonemethodexecute.ThisclassextendsBisCPwhichhasfewvariables.Wehavetoimplementexecutemethodinthisclassformanageattendanceusecase.Letslookintotheactualsourcecodeforthisclassnow.

packagecom.bis.cp;

importcom.bis.session.StudentAttendanceService;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

importjavax.servlet.http.HttpSession;

importorg.apache.log4j.Logger;

publicclassManageAttendanceCPextendsBisCPimplementsBisCommand{

staticLoggerlogger=Logger.getLogger(ManageAttendanceCP.class);

publicManageAttendanceCP(){

super();

}

publicStringexecute(HttpServletRequestrequest,HttpServletResponseresponse){

StringstrStudentId;

StringstrParamUpdateAttFrmSubmitted=“No”;//DefaultingtoNo.

strParamUpdateAttFrmSubmitted=request.getParameter(“paramUpdateAttFrmSubmitted”);

HttpSessionsession=request.getSession();

if(session!=null){

strStudentId=(String)session.getAttribute(“StudentId”);

if(strStudentId!=null){

StudentAttendanceServicestudentAttendanceService=newStudentAttendanceService();

if(strParamUpdateAttFrmSubmitted!=null&&strParamUpdateAttFrmSubmitted.equalsIgnoreCase(“Yes”)){

studentAttendanceService.updateStudentAttendance(request);

strNextNavigation=“ManageAttendance”;

}

try{

studentAttendanceService.processGetStudentAttendance(session);//GetsstudentattendanceforManageattendancepage.Thisincludesattendanceforboththesemesters.

strNextNavigation=“ManageAttendance”;//Thenextnavigationpageuponsuccessfulprocessing.

}catch(Exceptione){

logger.error(e.getMessage());

strNextNavigation=“Error”;//Thenextnavigationpageuponfailedprocessing.

}

}else{

//strStudentIdisnull,redirecttohomepagetoselectstudent.

strNextNavigation=“BisDashboard”;

}

}else{

//sessionisnull.Validsessiondoesn’texsit.RedirecttoLoginpage.

strNextNavigation=“Login”;

}

returnstrNextNavigation;

}

}

TheexecutemethodofManageAttendanceCPClass.

Theexecutemethodiscalledfromthecontrollerservlet.Thisisthejoboftheframework.TheframeworkgetsthecommandfromUIandbasedonthecommandloadsandexecutesaspecificcommandprocessorexploitingthepolymorphicfeatureofjava.Inthiscase,thecommandfromUIis“ManageAttendance”.Withintheservicemethodofcontrollerservlet,theManageAttendanceCPclassisloadedandinstantiatedandtheexecutemethodisinvoked.

Theexecutemethodperformsthefollowingtasks:

Getstheupdateattendanceformsubmittedflagfromtherequestparameter.ThisisYesincasetheuserhassubmittedtheupdateattendancerequestusingtheManageAttendance.jsp.ThisisNoincasetheuserhasrequestedthemanageattendancepageforthefirsttime.Inthiscase,themanagepagedisplaysexistingattendanceforagivenstudentforboththesemesters.

ChecksthevalueforparamUpdateAttFrmSubmittedparameter.

Ifyes,createsaninstanceofStudentAttendanceServiceandcallsupdateStudentAttendancemethod.Thismethodorchestratesanupdateofattendanceinthedatabase.Andfinally,setsthenextnavigationview.

Thelogicheredoesnotrequiretocheckfora“No”value.TheexecutemethodthancallsprocessGetStudentAttendance.Thismethodstakestheusertomanageattendancepageviewwiththeexistingattendancevaluesinthedatabase.ThejobofprocessGetStudentAttendanceistoonlyfetchtheattendancefromdatabaseanddisplayittotheuserintheManageAttendance.jsppage.Thisensuresthattheuserseesthelatestattendance.

Ifitsanupdaterequest,theupdateStudentAttendancemethodupdatestheattendanceinthedatabaseandtheuserisshowntheupdatedattendanceintheview.Ifitsnotanupdaterequest,thatis,iftheuserhasnavigatedtomanageattendancepageforthefirsttime.Theuserisshowntheexistingattendanceinthemanageattendancejsppage.

StudentAttendanceService.java

Pleaserefertogetstudentattendanceusecaseforthesourcecodeofthisclass.AlsoreferthesameusecaseforthedetaileddescriptionofprocessGetStudentAttendancemethod.

TheupdateStudentAttendancemethodperformsthefollowingtasks:

Cooksupthedynamicupdatequerywithplaceholdersforupdatingtheattendancetostudentattendancetable.

GetsthedatabaseconnectionfromDatabaseServiceclass.

Getsthepreparedstatementfromtheconnectionforthegivenquery.

Thesemesterandthenewattendancevaluesarefetchedfromtherequestparameters.ThesetXXXmethodsareusedtosetthesevaluestothepreparedstatement.

Thestudentidisfetchedfromthesessionandissettothepreparedstatementviaasettermethod.

Callsexecuteupdatemethodtoupdatetheattendanceinthestudentattendancetable.

Thedatabaseresourceswhichwereusedareclosedinthefinallyblock.

StudentAttendanceBean.java

Pleaserefertothegetstudentattendanceusecaseforthedetailsaboutthisbean.

ManageAttendance.jsp

ThisjspisdynamicallyincludedinBisHome.jspasaresultformanageattendanceusecaseinvocationthroughuserinteractionwiththeUI.

TillnowwehaveseenthatthecommandformanageattendancegoesformUIasaresultofuserinteraction.Thenthecontrollerservletcallsmanageattendancecommandprocessor.Thecommandprocessorcheckswhetheritisaninitialrequestforthemanageattendancepageorwhethertheuserhassubmittedanupdaterequest.Fortheformercase,thecommandprocessorrendersthemanageattendancejsppagewiththeexistingattendance.Andforthelatercase,thecommandprocessorutilizesmanageattendanceserviceclasstoupdatetheattendanceinthedatabase.

Themanageattendancejsppageprovidestwoeditabletextfieldsforupdatingattendanceforeachsemester.Thesetextfieldsdisplaytheexistingattendancevaluesandonceupdatedthesefieldsdisplaytheupdatedvalues.Thevaluesenteredbytheuserforthesetextfieldsarevalidatedattheclientsideusingjavascript.

HereisthesourcecodefortheManageAttendance.jspfile.

<%@pageimport=“com.bis.beans.StudentResultsBean,com.bis.beans.StudentAttendanceBean”%>

<%@pageimport=“java.util.Hashtable,java.util.Enumeration”%>

<%

StudentResultsBeanstudentResultsBean=null;

intinPresentPercentage=0;

intinTotal=0;

intinPresent=0;

StudentAttendanceBeanstudentAttendanceBean=null;

if(session!=null){

studentResultsBean=(StudentResultsBean)session.getAttribute(“studentResultsBean”);

studentAttendanceBean=(StudentAttendanceBean)session.getAttribute(“studentAttendanceBean”);

}

if(studentAttendanceBean!=null){

inTotal=studentAttendanceBean.getTotalWorkingDays();

inPresent=studentAttendanceBean.getAttendance();

if(inTotal>0&&inPresent>0){

inPresentPercentage=Math.abs(100*inPresent/inTotal);

}

}

%>

<formid=“frmManageAttendance”name=“frmManageAttendance”method=“POST”action=“BisControllerServlet”>

<inputtype=“hidden”name=“ParameterActionCommand”value=“ManageAttendance”></input>

<inputtype=“hidden”name=“ParameterUpdateSemAttendance”id=“ParameterUpdateSemAttendance”></input>

<inputtype=“hidden”name=“paramUpdateAttFrmSubmitted”id=“paramUpdateAttFrmSubmitted”value=“No”></input>

<tableborder=“0”cellpadding=“10”cellspacing=“0”width=“100%”>

<tr><td>&nbsp;</td></tr>

<tr>

<tdalign=“center”colspan=“3”id=“whiteBg”>

ManageAttendance

</td>

</tr>

<tr><td>&nbsp;</td></tr>

<tralign=“center”>

<tdheight=“250px”>

<tableborder=“1”cellpadding=“10”cellspacing=“0”width=“80%”>

<tr>

<tdalign=“center”colspan=“3”id=“trbgred”>

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getFullName());

}

%>

&nbsp;&nbsp;|&nbsp;&nbsp;

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getGrade());

out.print(”-“);

out.print(studentResultsBean.getSection());

}

%>

&nbsp;&nbsp;|&nbsp;&nbsp;

<%

if(studentResultsBean!=null){

out.print(studentResultsBean.getStudentId());

}

%>

</td>

</tr>

<tralign=“center”id=“whiteBg”>

<tdwidth=“50%”>

<tableborder=“0”cellpadding=“5”cellspacing=“0”width=“60%”>

<tr><tdcolspan=“3”>&nbsp;</td></tr>

<tr><tdcolspan=“3”>&nbsp;</td></tr>

<tr>

<tdalign=“center”colspan=“3”id=“trbgred”>

Semester-I

</td>

</tr>

<trvalign=“middle”>

<tdalign=“right”width=“45%”>

Totalworkingdays

</td>

<tdwidth=“10%”>&nbsp;</td>

<tdwidth=”*”align=“left”>

<%

if(studentAttendanceBean!=null){

out.print(studentAttendanceBean.getSemOneTotalWorkingDays());

}

%>

</td>

</tr>

<trvalign=“middle”>

<tdalign=“right”>

Present

</td>

<td>&nbsp;</td>

<td>

<inputtype=“text”id=“txtPresentSemOne”name=“txtPresentSemOne”size=“12”

value=”<%

if(studentAttendanceBean!=null){

out.print(studentAttendanceBean.getSemOneAttendance());

}

%>”/>

</td>

</tr>

<trvalign=“middle”>

<tdalign=“right”>

Absent

</td>

<td>&nbsp;</td>

<td>

<%

if(studentAttendanceBean!=null){

intintAbsent=studentAttendanceBean.getSemOneTotalWorkingDays()-studentAttendanceBean.getSemOneAttendance();

out.print(intAbsent);

}

%>

</td>

</tr>

<trvalign=“middle”>

<tdalign=“center”colspan=“3”id=“trbgred”>

<inputtype=“button”name=“btnUpdAttSem1”value=”Update”id=“btnUpdAttSem1”onclick=“updateAttendance(‘1’)”/>

</td>

</tr>

<tr><tdcolspan=“3”>&nbsp;</td></tr>

<tr><tdcolspan=“3”>&nbsp;</td></tr>

</table>

</td>

<tdwidth=”*”>

<tableborder=“0”cellpadding=“5”cellspacing=“0”width=“60%”>

<tr><tdcolspan=“3”>&nbsp;</td></tr>

<tr><tdcolspan=“3”>&nbsp;</td></tr>

<tr>

<tdalign=“center”colspan=“3”id=“trbgred”>

Semester-II

</td>

</tr>

<trvalign=“middle”>

<tdalign=“right”width=“45%”>

Totalworkingdays

</td>

<tdwidth=“10%”>&nbsp;</td>

<tdwidth=”*”align=“left”>

<%

if(studentAttendanceBean!=null){

out.print(studentAttendanceBean.getSemTwoTotalWorkingDays());

}

%>

</td>

</tr>

<trvalign=“middle”>

<tdalign=“right”>

Present

</td>

<td>&nbsp;</td>

<td>

<inputtype=“text”id=“txtPresentSemTwo”name=“txtPresentSemTwo”size=“12”

value=”<%

if(studentAttendanceBean!=null){

out.print(studentAttendanceBean.getSemTwoAttendance());

}

%>”/>

</td>

</tr>

<trvalign=“middle”>

<tdalign=“right”>

Absent

</td>

<td>&nbsp;</td>

<td>

<%

if(studentAttendanceBean!=null){

intintAbsent=studentAttendanceBean.getSemTwoTotalWorkingDays()-studentAttendanceBean.getSemTwoAttendance();

out.print(intAbsent);

}

%>

</td>

</tr>

<trvalign=“middle”>

<tdalign=“center”colspan=“3”id=“trbgred”>

<inputtype=“button”name=“btnUpdAttSem2”value=”Update”id=“btnUpdAttSem2”onclick=“updateAttendance(‘2’)”/>

</td>

</tr>

<tr><tdcolspan=“3”>&nbsp;</td></tr>

<tr><tdcolspan=“3”>&nbsp;</td></tr>

</table>

</td>

</tr>

</table>

</td>

</tr>

<tr><td>&nbsp;</td></tr>

</table>

</form>

Thisconcludesthemanageattendanceusecaseimplementationfromendtoend.Wecomposedtherequirementspecifications,webuilttheprototype,wefollowedthearchitectureforthesolution,weleveragedtheframework,wedevelopedthevariousjavaclasses,weusedthecommoncomponentslikeDatabaseService.java,BISStyle.cssetcandwebuilttheviewwiththejsppage.

16SECURINGAPPLICATION

Securityisoneofthemostimportantaspectofanyapplication.InoursampleapplicationBIS-SMSweneedtoensurethatonlyauthenticatedusersareallowedtoaccesstheapplication.

Onceauthenticatedausercanaccesstheapplication.Thenextthingthatneedstobeidentifiedisauthorization.Anauthenticatedusermaynothaveprivilegestoaccesseverythingintheapplication.Thisisgovernedbyuserroles.Rolesdefinetheaccessprivilegetoaparticularserviceordata.Fore.g.auserwithadministratorrolecanaddanewstudentwhereasauserwithteacherrolecanonlyviewastudent.Authorizationdictatestherolesandrolesinturncontroltheaccessrights.Inourapplicationwewilldefinerolesaspertherequirementsspecificationsforauthenticationandauthorization.

ConfiguringdatasourcesecurityrealmforApacheTomcat8

Wewillusecontainermanagedsecurityforourapplication.Thatis,inourcasetheauthenticationandauthorizationisprovidedoutoftheboxbyApacheTomcat8server.Wewillonlyconfigurethesecurityforourapplication.FollowingstepsarerequiredtoconfigurecontainermanagedsecurityforawebapplicationinApacheTomcat8server.

Step1:CreateTables

Weneedastorageforusernames,passwordsanduserroles.Thisisknowasarealm.Forthiswewillusedatabase.WeareusingseparateschemafordatabasesecurityrealmcalledBisSecurityRealm.Pleasereferchapter9databasedesignfordetailsaboutthedatabasedesignforBisSecurityRealmschema.Onceyoucreatethisschemaandallthetablesyoumayproceedtothenextstep.

[Note:Thescriptstocreatethedatabasetablesisprovidedinchapter22undertheappendixsectionfordatabasescripts.]

Step2:Createdatasource

ThisdatasourcemustpointtotheBisSecurityRealmschema.Thisdatasourceisusedby

servertoreadusername,passwordandroles.

Inordertocreatethedatasource,addthefollowingentrytoserver’scontextdescriptorfilelocatedat$CATALINA_BASE/conf/context.xml.

<Resource

name=“jdbc/BisSecurityRealmDS”

auth=“Container”

maxActive=“20”

maxIdle=“5”

maxWait=“10000”

factory=“oracle.ucp.jdbc.PoolDataSourceImpl”driverClassName=“oracle.jdbc.OracleDriver”url=“jdbc:oracle:thin:BisSecurityRealm/Welcome01@127.1.1.0:1521:XE”type=“oracle.ucp.jdbc.PoolDataSource”

connectionFactoryClassName=“oracle.jdbc.pool.OracleDataSource”connectionPoolName=“SecurityUCPPool”

validateConnectionOnBorrow=“true”

sqlForValidateConnection=“select1fromDUAL”/>

Youneedtomakesurethatthevalueforurlattributepointstoyourdatabaseanduser.jdbc:oracle:thin:userId/pwd@host:port:sid

e.g.jdbc:oracle:thin:BisSecurityRealm/Welcome01@127.1.1.0:1521:XE

Restarttheserverfortheavailabilityofthedatasource.

Step3:Add<relam>elementtoserver.xmlfile.

Goto$CATALINA_BASE/conf/folderandopenserver.xmlfile.Addthefollowingrealmtagentrytothisfile.

<Realm

className=“org.apache.catalina.realm.DataSourceRealm”dataSourceName=“jdbc/BisSecurityRealmDS”

userTable=“users”

userNameCol=“user_name”

userCredCol=“user_pass”

userRoleTable=“user_roles”

roleNameCol=“role_name”

localDataSource=“true”/>

Here’sthedescriptionoftheattributes:

className:Identifiesthetypeofrealm.

dataSourceName:ThenameofthedatasourcewhoseconnectionsareconfiguredforBisSecurityRealmschema.

userTable:Nameofthetablewhichisholdingtheusernamesandpasswords.

userNameCol:ThecolumnwithinuserTablewhichholdstheusernames.

userCredCol:ThecolumnwithinuserTablewhichholdstheuserpassword.

userRoleTable:Thetablewhichholdstheuserroles.

roleNameCol:ThecolumnwithinuserRoleTablewhichholdstherolenames.

Savetheserver.xmlfileandrestarttheserver.

Wemadetwoentriesinconffolder.Oneintheserver.xmlfileforrealmconfigurationandtheotherincontext.xmlfordatasourceconfiguration.

Step4:Verification

TotestinserttheuserYousuf.BaigandpasswordWelcome01touserstable.Now,addtherolenamesadmin-gui,admin-scriptandmanager-guitouser_rolestablefortheuserYousuf.Baig.

Gototheserverhomepageandclickmanagerapplinkontherighthandside.Theserverwillchallengeyouforauseridandpassword.EnterYousuf.BaigasuserandWelcome01aspasswordandpressenter.Theserverwillverifytheuserandpasswordinthedatabaseandifvalidateditwilllookfortheroles.Andsincewehaveaddedtherolesforthisuseritwilltakeyoutothemanagerapppage.

EnablingSecurityforBIS-SMSAddingentriestoapplicationweb.xmlforsecurityenablement.

Tousethecontainermanagedsecuritywiththeaboveconfigurations,wenowneedtoconfiguretheapplicationtoleveragethecontainermanagedsecurityofApacheTomcat8.

Inordertodothisweneedtoaddfewentriestotheweb.xmlfileofthesampleapplication.Wewillnowaddthefollowingentriestoweb.xmllocatedatWEB-INFfolderofthesamplewebapplicationBIS-SMS.

<security-constraint>

<web-resource-collection>

<web-resource-name>

Wildcardmeanswholeapplicationrequiresauthentication

</web-resource-name>

<url-pattern>/*</url-pattern>

<http-method>GET</http-method>

<http-method>POST</http-method>

</web-resource-collection>

<auth-constraint>

<role-name>BisAdmin</role-name>

<role-name>BisTeacher</role-name>

<role-name>BisClerk</role-name>

</auth-constraint>

<user-data-constraint>

<transport-guarantee>NONE</transport-guarantee>

</user-data-constraint>

</security-constraint>

<login-config>

<auth-method>FORM</auth-method>

<form-login-config>

<form-login-page>/BisLogin.jsp</form-login-page>

<form-error-page>/BisLogin.jsp</form-error-page>

</form-login-config>

</login-config>

<welcome-file-list>

<welcome-file>BisLandingPage.jsp</welcome-file>

</welcome-file-list>

The<welcome-file-list>typicallyhasoneentryforthelandingpageuponsuccessfulauthenticationoftheuser.Theserverautonavigatestheusertothispageonceauthorized.

The<auth-method>withinthe<login-config>tagspecifiestheauthenticationmethod.HerewewillspecifyFORMsincewehaveBisLogin.jspfileforformbasedauthentication.

Inthe<form-login-page>tagwewillspecifyourloginpagewhichisBisLogin.jsp

Withinthe<auth-constraint>tagunder<security-constraints>weneedtograntaccessoftheapplicationtoalistofroles.Notethatwehavetospecifyalltherolesthatwewanttouseinthisapplication’sauthorization.Youmayhavemanyrolesinthedatabase.Someofthemmightbeusedbyotherwebapplications.Thedatabaseisgenerallyacentralizedrepositoryofalltheusersandrolesinanenterprise.Eachapplicationwillaccessitsownusersandroles.

LDAPserversaretypicallyusedinlargeenterprisesassinglesourceofinformationforalltheusersandroles.OracleOIDandMicrosoftADarethemostpopularexamplesofdirectoryservicesused.WearenotusinganyLDAPservicesforourapplication.However,thiscanbeachievedwithitsspecificconfigurations.

Withthiswearedonewiththeenablementofcontainermanagedsecurityofoursampleapplication.Redeploytheapplicationwiththenewmodifiedweb.xmlfile.

BIS-SMSUsersandRoles

Wewillnowaddthefollowingusersandrolestothedatabaseforoursampleapplication.Pleaserefertotherequirementsspecificationtablefortherolesdetails.

Intheauthorizationusecaseimplementation,wewillseehowthedashboardandlinksarerenderedtoeachofthisuserbasedontheirroles.

17BUILDANDDEPLOYMENT

Onceawebapplicationisready,ithastobebuilt,packagedandthendeployedtotheserver.

Areadywebapplicationisnothingbutasetofrefinedfiles.Thesefilesaretypicallyjava,Servlets,jsps,.css,xmlandJavascript.Allthesefileshavetobepackagedasperstandardsandthenfinallydeployedtotheserver.

TheWebApplicationArchiveAsperJEEdeploymentspecifications,weneedtobuilda“.war”fileforourapplication

whichcanbedeployedtotheservletcontainer.warstandsforWebAchieve.Inourcase,weneedtobuildBis.warfile.

The.warfilecomprisesof:

AlltheHTML/JSPfiles

Allthecompliedjavaclasses

Allthelibrariesreferenced(ifany)intheformof.jarfiles

Thedeploymentdescription(web.xmlfile)

Thecontextfile

Propertiesfiles

Allthe.cssand.jsfiles

Manifestfile

A.warfilebuildbasedonstandardscanbedeployedtoanyserverwhichiscompliantwiththestandards.TheBis.warfilewearebuildingasapartofexerciseisbasedonJEEstandards.SinceBis.wariscompliantwithJEEstandards,itcanbedeployedtoanyserverwhichisJEEcompliant.Hence,wecandeploythewebachieveofourapplicationtoWeblogic,Websphere,ApacheTomcatortoanyJEEcomplaintserver.

Now,wehavetwothings.One,buildtheBis.warfileandtwo,deployittoApacheTomcat

server.

BuildingtheBis.warfile

Therearevariousmethodstobuildthe.warfile.ThesimplestandeasiestistouseanIDElikejdeveloper.Inourcase,wewillusejdevelopertobuildtheBis.warfile.

BuildBis.warwithjdeveloper

Step1:RightclickBisViewControllerprojectandselectprojectpropertiesasshowninthefigurebelow.

Step2:Onthelefthandside,selectDeploymentandontherighthandsideclicknewasshowninthefigurebelow.

Step3:Selectwarfileundertheprofiletypedropdownmenuandprovideaname(Bis)fordeploymentprofile.Clickok.

Step4:SelectSpecifyJavaEEWebContextRootradiobuttonandspecifythecontextrootas“Bis”.Leaveeverythingasitisandclickok.Youwillnowseethedeploymentprofilelisted.Clickoktoclosetheprojectpropertiesdialogue/wizard.Saveallandproceedtonextsteps.

Step5:RightclicktheBisViewControllerprojectandselectDeploythanBis.Inthewizard,select“DeploytoWAR”andclickfinish.

Step6:Onceyouclickfinish,jdeveloperwillpreparetheBis.warfileforyouandthelogwilltellyouwherethefileislocated.Gotothefolderandverifythepresenceofthewarfile.

Thiscompletesthepreparationofthewarfile.Now,letsdeploythiswarfiletoApacheTomcatserver.

Deployingthe.warfile

Thewarfilecanbedeployedinvariousways.Themostcommonpracticeistouseantscriptfordeployment.TheothereasywayofdoingitisusingtheGUIbaseddeploymentmanagerapplicationthatcomeswithmostoftheservers.Inourcase,wewillusetheManagerApptodeployBis.warfiletoApacheTomcat.

DeployingBis.wartoApacheTomcat

Step1:Makesurethattheserverisrunning.Launchthebrowserandgotothehomepageoftheserver.Click“ManagerApp”asshowninthefigurebelow.

Step2:Theserverwillchallengeyouforuser/password.Providetheadminuserandpasswordtoproceed.Uponsuccessfulauthenticationandauthorization,youwillseetheapplicationmanagerpage.Click“ChooseFile”buttonbelowfor“SelectWARfiletoupload”asshowninthefigurebelow.

Step3:Onceyoubrowsethewarfile,clickdeploy.Theserverwillnowdeploythewarfileanduponsuccessfuldeploymentitwillimmediatelyrefresh.Now,youshouldseedeployedapplicationunderthelistwiththerunningstatus“true”asshowninthefigurebelow.

Step4:Now,openabrowserandgotothefollowingurlhttp://<host>:<port>/Bis

Example:http://localhost/Bis.Thisshouldloadtheloginpageoftheapplication.

Theotherimportantfilesthatneedstobeunderstoodforbuildanddeploymentarebuild.xml,context.xmlandlog4j.properties.Pleasereferchapter21fordescriptionandusageofthesefiles.

18TESTING

Asthenamesuggests,testingisverifyingwhetherthesystembuiltisaspertherequirementsspecification.Forourapplicationweneedtwotypeoftesting,unittestingandsystemtesting.

UnitTestingTheunittestingneedstobeperformedbythedeveloperfortheindividualusecases.

Forexample,thedeveloperwhobuildsthemanageattendanceusecasemustverifywhetherthisusecaseisworkingexactlyasperthecorrespondingrequirementsspecifications.Ideally,theimplementedusecasemustsatisfyalltherequirements,itshouldbeerrorfreeandmustnothaveanybugs.Agooddeveloperleavesnostoneunturnedtomakesurethattheusecaseimplementedbyhim/heris100%bugfreeand100%incomplianceaspertherequirementspecificationsforthatusecase.

SystemTestingThesystemtestingtobeperformedbythetestingteam.Oncealltheusecasesare

implementedbythedevelopers,thesolutionsarchitectassemblesthemallanddeploysthespecificversionofcompletesoftwaresolutiontothetestingenvironment.ThissolutioniscompleteandthisistheonewhichgoestotheUATandthantotheproduction.Thetestingteamperformsrigoroustestingonthetestingenvironmentandlogstheissues,observationsandbugs.Thisgoesbacktothedevelopmentteam.Thedevelopmentteamfixesthesebugsandanewversionisdeployedtothetestingenvironment.Thetestingteamonceagainperformsallthetestsonthisversionandreportsbackbugorregressionstothedevelopmentteam.Thisisacyclicprocessandwitheachcyclethequalityofthesoftwareimproves.

UserAcceptanceTesting(UAT)

OnceanacceptablepointisachievedthesolutionisdeployedtotheUATenvironmentforuseracceptancetesting.Inthistesting,theclientprimarilyverifiesthatthesoftwaresolutionisaspertheirrequirementsandexpectations.Postapprovalofthisthesoftwaresolutionisdeployedtotheproductionenvironment.Upongo-livethesolutionbecomeusablefortheendusersandtheenduserswillstartusingthesoftwaresolutionorweb

applicationinourcase.Errorsmayhappeneveninproductionifthesoftwarelackspremiumquality.Thesupportteamprovidesproductionsupportandtakescareoftheissuesontheproductionenvironment.

19DEBUGGING

Whatisabug?

Abuginsoftwareisanerror,amalfunction,aflaw,afaultorafailureeitherwiththebusinesslogicorwiththesoftwarecode.Thebugresultsinfunctioningofthesoftwarecodeinanunexpectedwayornotaspertherequirementsorexpectations.

StepstoresolveabugTheprocessofidentifying,analyzing,reproducingandfixingabugiscalled

debugging.Lesserthenumberofbugs,higherthequalityofthesoftware.Letslearntoresolveabugwithapracticalexamplefromoursampleapplication.

Describethebug

Whiletestingtheusecaseupdateattendance,thesampleapplicationisfailingtoupdatetheattendance.

Reproducethebug

1. LogintotheBIS-SMSsamplewebapplicationwiththeuserpadma.kulkarniwhohasBisAdminrights.

2. LoadthestudentintocontextwhoseidisMyFaAsYo12042004.3. Gotomanageattendancepage.4. Forsemestertwo,thecurrentvalueofattendanceis0.Updateitto105andclick

submitbutton.5. Aspertherequirementsspecification,thispageshouldnowdisplay105asupdated

attendanceforthegivenstudentandsemester.Thepageisratherdisplayingthesameoldvaluei.e.0insteadof105.

Reproducetheissueonyourenvironment.Makesurethatyourenvironmentandtheclient’senvironmenthassameversionoftheapplicationandalsothesameversionand

samesetofpatches.Apatchcomprisesofoneormoremodifiedjavaorotherfilesbelongingtotheapplication.

Diagnosisandresolution

Afterensuringthatthereisnodiscrepancyinversionandpatchesreproducetheissue.Letsassumethattheissuesisreproducedonthetechnicalsupportteam’senvironment.Now,itistimetofigureoutwhytheattendanceisnotgettingupdatedinthedatabasetable.Thisisthebuganalysisphase.Opentheapplicationlogfileandlookforthemessagesorexceptionsrelatedtothisusecase.

Thelogfilehasthefollowingrelevantmessage:

“Theupdatecountforattendanceupdateis:0”

Thismeansthattheupdateoperationisfailing.Otherwisetheupdatecountwouldhavebeen1insteadof0.

Letsnowopenthejavaclasswheretheupdatequeryiscalled.ThisisthereinStudentAttendanceService.java.Weidentifiedthisbecauseweknowthatinourapplicationthedatabaseoperationsareperformedbytheserviceclasses.IncaseofnoclueabouttheexactjavafilewecanuseadebuggerintheIDEwithabreakpointatapointofsuspicioninthecode.Ifnotsurewheretoplacethebreakpoint,onecansetitatthecontrollerservletlevel.

WithintheupdateStudentAttendancemethodwehavethisquery.UPDATESTUDENT_ATTENDANCESETATTENDANCE=?WHERESTUDENT_ID=?ANDSEMESTER=?

Wewillnowexecutethisquerywithourvaluesatasqlclientforthegivendatabaseandschema.Thequerytobeexecutedis.

UPDATESTUDENT_ATTENDANCESETATTENDANCE=105WHERESTUDENT_ID=‘MyFaAsYo12042004’ANDSEMESTER=2

Thesqlclientnowsays,0rowsupdated.Themostlikelycauseisthattherecordpertainingtothewhereconditionsmightnotbeexistinginthestudentattendancetable.Toverifythisletsexecutethefollowingquery.

SELECT*FROMSTUDENT_ATTENDANCEWHERESTUDENT_ID=‘MyFbAsYo12042004’andSEMESTER=2;

Thisqueryisnowreturningzerorows.Thisconfirmsthattherecordforthewhereconditionsisnotthereinthestudentattendancedatabasetable.Thenextquestioniswhythepageisdisplayingzerofortheattendancewhenthereisnorecordavailableinthedatabasetable.Analyzingthecoderevealsthatthepagedisplayszeroifattendanceisnotfoundinthedatabasetable.

Wenowknowthereasonforthebug.Letsfixthisbugnow.Inordertoupdatetheattendanceforagivenstudentandsemesterarecordmustbeexistinginthestudentattendancetable.Aftercarefulanalysisanothervitalinformationisrevealedthatthisbugisonlyhappeningforthenewlyaddedstudentsusingaddnewstudentusecase.

Theaddnewstudentasofnowisinsertingrecordsviadatabasetransactiontotwodatabasetablesstudentdetailsandparentdetails.Foreverynewstudent,weneedtoinsertarecordtostudentattendancetablewithinitialvalueforattendanceaszeroforeachsemester.

WriteaseparatemethodinAddStudentService.javaclasscalledinsertNewStudentToSAandincludethatinthenewstudentcreationdatabasetransaction.

Verifyingthefix

Addanewstudentusingtheaddnewstudentusecase.Thisnowaddstworecordstothestudentattendancetableforthisnewstudent.Now,gotomanageattendancepageandupdatetheattendanceforeachsemester.Theupdatequerywillnotfailastherearerecordstobeupdatedforthegivenwherecondition.Thisconfirmsthattheissuesisresolvedandthebugisfixed.

Applyingthepatch

Oncethebugisfixedweneedtopatchtheclientenvironment.Thisisdonebyreplacingthemodifiedjavafileswiththeexistingjavafiles.Identifythejarfiletowhichthesefilesbelong.Shiptheupdatedjarfiletotheclient.Oncetheclientreplacestheoldjarfilewiththenewone.Thebugisfixedonthatenvironment.

20OTHERIMPORTANTTOPICS

AJAX

Inmanycaseswhenauserinteractswithawebpage,itisnotatallnecessarytoreloadtheentirepagejusttochangeavieworavalueinasmallregionofthepage.Insuchcasesonlyrefreshingasmallregionofthepagewillsuffice.Refreshingaregionhaslotsofadvantagescomparedtoreloadingtheentirepage.Itsavestime,reducesnetworktraffic,savesinternetdataconsumption,reducesburdenontheserveretc.Themostimportantadvantageisthattheuserfeelsasifthingsarerealtime.

ThisprogrammingparadigminwhichawebpageispartiallyrefreshedbasedontheuserinteractionisachievedthroughacombinationofvarioustechnologiesanditiscalledAJAX.AjaxstandsforAsynchronousjavascriptandxml.

InAJAXwhenauserinteractswithawebpage,ajavascriptfunctionisinvokedonthebrowsersideitself.ThisjavascriptfunctionutilizesXMLHttpRequestobjecttointeractwiththeserverviaAjaxrequest.Theserverreturnstheresponsetext.Thisresponsetextfortheajaxrequestisconsumedbythejavascriptcallbackfunction.Thisfunctioninturnusestheresponsetexteitherforcomputationorfordirectdisplayontheregionofthepage.TheregionofthewebpageisthenrefreshedenablingtheusertoseetheAjaxresponseforaparticularuserinteraction.

Hence,AjaxhastwopartsoneontheclientsidewhereXMLHttpRequestjavascriptobjectisleveragedandtwoontheserversidewherethehttprequestisrespondedwitharesponsetext.

Foradetailedimplementationwithdesignandcodepleaserefertheusecaseimplementationforloadstudentinchapter15.

Performancetuningandbestpractices

Thefollowingmeasureshelpinincreasingtheperformanceofthewebapplication:

1. Keeptherenderedhtml/jsppagesaslightaspossible.Thewebpagesbuildusingide’sgenerallyaddlotsofredundantandunnecessaryhtmltags.Makesurethatthepageshaveonlythosetagsandattributeswhicharerequired.

2. UseAjaxwhereverapplicable.3. Applyallthebestpracticesforjavacodedevelopmentattheserverside.4. Release/Closeresourcesimmediatelyaftertheusage.5. Handleeverysingleexceptioninthecode.6. Useloggingasifyouaregoingtoprovidetechnicalsupporttotheapplication

aftergoinglive.7. Evolvethedatabasedesignasmuchhaspossible.8. Cleanupunusedvariablesandfunctionsinthejavascript(.js)file.9. Cleanupalltheunusedstylesinthecascadedstylesheet(.css)file.

10.Usedatasourcesforinteractionwithdatabases.11.Inabusinesscriticalapplicationperformvalidationbothattheclientsideaswellastheserverside.12.Usepagetemplateswhereverpossible.13.Leverageprovenarchitecturalanddesignpatterns.14.Reusehtmlpagesfromtheprototypeforbuildingtheactualjsppages.15.Optimizetheserverforperformancefollowingrecommendedpracticesinthespecificserver’sadministrativeguide.Onesuchexampleisincreasingtheheapmemorysizefortheserver.16.Becomplaintwiththerecommendationsfortheframeworkused.Thiswillbehelpfulforframeworkupgrades.Otherwise,therewillbeissuesandtheupgradewillnotbeseamless.

Scalability

Asoftwaresolutionthathasprovisionstoeasyextendorenhanceitforfuturerequirementsiscalledascalablesystem.Scalabilityisanimportantfactorforanysoftwaresolutiondesign.Rigidsystemsrequirelotsofhumaneffort,rework,cost,downtimeetcwhereasscalablesystemsareflexibletoenhance.

Forthesampleprojectwebuiltinthisbook,incasewewanttoaddcoupleofnewusecaseswehavetojustbuildajspview,serviceclass,commandprocessorandbeansincompliancewiththeframeworkandthenewusecasebecomespluggable.Thesampleapplicationalongwithourframeworkisscalable.Hence,wecanextendorenhanceitwithease.Wecaneasilyaddanynumberofusecasestooursampleapplicationinfuturebecauseitisdesignedtobehighlyscalable.Scalabilityneedstobekeptinmindatthearchitectureanddesignstage.

Apracticalexampleofscalabilityismoderndaydesktopcomputer’smotherboard.Thesemotherboardscomeupwithopenslotsformemory(RAM).Onceyoupurchaseadesktopwith4GbRAM,itcanbelaterscaledupto16or32GbofRAMjustbyinsertingmemorycardsintheopenslotsprovided.Incaseofnonscalablemotherboards,theuserhastobuyanewmotherboardordesktopitselfwiththenewrequirementforthememory.

21IMPORTANTFILES

Besidesthejavaclasses,jsps,.cssand.jsfilesadeploymentreadywebapplicationhasfewotherimportantfilesandfolder.Inthischapterwewillhaveacloserlookatalltheseimportantfilesandfoldersthataremusttohaveasmoothanderrorfreedeploymentandexecutionoftheapplication.

web.xml

Generally,manywebapplicationsaredeployedtoaserver.Eachwebapplicationhasitsownsetofcustomizations,propertiesandotherJEEconfigurations.Inordertospecifythesethingstotheserver,eachwebapplicationispackagedwithadeploymentdescriptorwhichisnothingbutanxmlfile.Thisxmlfileiscalledweb.xmlasperJavaServletspecification.

InJavaPlatformEnterpriseEdition,theweb.xmlfile(deploymentdescription)describeshowawebapplicationshouldbedeployedtothecontainer.Theweb.xmlresidesintheWEB-INFfolderofthewebapplicationroot.

Letslookintotheimportanttagsandattributesofthewebapplicationdeploymentdescriptor(web.xml).Forthisletsusetheweb.xmlfileofBIS-SMSsamplewebapplication.

Describesthecontrollerservlet.

<servlet>

<servlet-name>ControllerServlet</servlet-name>

<servlet-class>com.bis.servlet.ControllerServlet</servlet-class>

</servlet>

DescribestheAjaxcontrollerservlet.

<servlet>

<servlet-name>AjaxControllerServlet</servlet-name>

<servlet-class>com.bis.servlet.AjaxControllerServlet</servlet-class>

</servlet>

Describesthemappingforcontrollerservlet.

<servlet-mapping>

<servlet-name>ControllerServlet</servlet-name>

<url-pattern>/BisControllerServlet</url-pattern>

</servlet-mapping>

DescribesthemappingforAjaxcontrollerservlet.

<servlet-mapping>

<servlet-name>AjaxControllerServlet</servlet-name>

<url-pattern>/BisAjaxControllerServlet</url-pattern>

</servlet-mapping>

Describestheresourcereferenceforapplication(BIS)datasource.

<resource-ref>

<description>BISDatasource</description>

<res-ref-name>jdbc/bisDataSource</res-ref-name>

<res-type>javax.sql.DataSource</res-type>

<res-auth>Container</res-auth>

</resource-ref>

Context.xml

ApacheTomcatservletcontainerdoesnotprovideanyGUItocreateconnectionpoolsanddatasources.Thisisachievedviaaresourcetagentryincontext.xmlfile.

Thecontext.xmlfilesareapplicationspecificaswellasatserverlevel.Theoneatserverlevelislocatedat$CATALINA_BASE/conf/context.xml.Forconfiguringdatasource

securityrealmweneedtoaddthedatasourceresourceentrytothisfile.Thisisdetailedinthechaptertitledsecuringapplicationundertheconfigurationheading.AndtheonespecifictoapplicationisundertheMETA-INFfolderofthesubjectiveapplication.

Weneedtoaddentriestotwocontextdescriptorsforourapplication.

Oneintheservercontextdescriptorlocatedat$CATALINA_BASE/conf/context.xmlandotherintheapplicationcontextdescriptorlocatedat$CATALINA_BASE/webapps/Bis/META-INF/context.xml

Anentryisaddedtoserver’scontextdescriptorfileforadatasourcewhichisusedbythecontainermanagedsecurityprovider.Thisdatasourceisusedforauthenticationandauthorizationpurposebytheserver.

Weneedtoaddanentrytothecontext.xmlfilebelongingtooursampleapplicationwhichislocatedwithinthe/Bis/META-INFfolder.Thisentrycreatesadatasourcetobeusedinoursampleapplication.Theconnectionsreturnedbythisdatasourcewillprovideusaccesstoourapplicationtables.

<Resourcename=“jdbc/bisDataSource”auth=“Container”maxActive=“20”maxIdle=“5”maxWait=“10000”factory=“oracle.ucp.jdbc.PoolDataSourceImpl”

driverClassName=“oracle.jdbc.OracleDriver”url=“jdbc:oracle:thin:bis/bis@127.1.1.0:1521:XE”type=“oracle.ucp.jdbc.PoolDataSource”

connectionFactoryClassName=“oracle.jdbc.pool.OracleDataSource”connectionPoolName=“BisPool”validateConnectionOnBorrow=“true”

sqlForValidateConnection=“select1fromDUAL”/>

Theaboveentryinthecontext.xmlfileofourapplicationwillcreateadatasourcecalledbisDataSource.WeperformaJNDIlookupforthisdatasourceinourapplication.PleaserefertheDatabaseService.javaclassinthecomponentschapterfortheactualcodetolookupthisdatasource.

ThedriverclassnameisspecifiedasOracleDriverbecauseweareusingOracledatabase.TheURLpointstolocalhostwiththeport1521wherethesystemidentifierfordatabaseinstance(SID)namedXEisrunning.And“bis”isthedatabaseschemaname.

22APPENDIX

Databasescripts

Schema:BisSecurityRealmCREATETABLEUSERS

(

USER_NAMEVARCHAR2(15BYTE)NOTNULL

,USER_PASSVARCHAR2(15BYTE)NOTNULL

,CONSTRAINT“User_Name_PK”PRIMARYKEY

(

USER_NAME

)

ENABLE

)

CREATETABLEUSER_ROLES

(

USER_NAMEVARCHAR2(15BYTE)NOTNULL

,ROLE_NAMEVARCHAR2(15BYTE)NOTNULL

,CONSTRAINT“User_Roles_CPK”PRIMARYKEY

(

USER_NAME

,ROLE_NAME

)

ENABLE

)

ALTERTABLEUSER_ROLES

ADDCONSTRAINTUSER_NAME_FKFOREIGNKEY

(

USER_NAME

)

REFERENCESUSERS

(

USER_NAME

)

ENABLE;

Schema:bisCREATETABLEBIS_CONSTANTS

(

PROPERTYVARCHAR2(30BYTE)

,VALUEVARCHAR2(80BYTE)

,REMARKSVARCHAR2(60BYTE)

)

CREATETABLECLASS_TEACHER_MAPPING

(

EMPLOYEE_IDNUMBER

,GRADEVARCHAR2(4BYTE)NOTNULL

,SECTIONVARCHAR2(1BYTE)NOTNULL

,CONSTRAINTCTM_CPKPRIMARYKEY

(

GRADE

,SECTION

)

ENABLE

)

CREATETABLECOSCHOLASTIC_RESULTS

(

STUDENT_IDVARCHAR2(16BYTE)NOTNULL

,SEMESTERVARCHAR2(1BYTE)NOTNULL

,CRITICAL_THINKINGVARCHAR2(15BYTE)

,CREATIVE_THINKINGVARCHAR2(15BYTE)

,COLLAB_LEARNINGVARCHAR2(15BYTE)

,COMMUNICATION_SKILLSVARCHAR2(15BYTE)

,COMPREHENSIVE_GROWTHVARCHAR2(15BYTE)

,INTELLI_QUOVARCHAR2(15BYTE)

,EMO_QUOVARCHAR2(15BYTE)

,SOCIAL_QUOVARCHAR2(15BYTE)

,HEALTH_QUOVARCHAR2(15BYTE)

,COMMUNITY_CONSCVARCHAR2(15BYTE),SCHOLASTICPERFORMANCE_REMVARCHAR2(300BYTE)

,COSCHOLASTICPERFORMANCE_REMVARCHAR2(300BYTE)

,CONSTRAINTCSR_CPKPRIMARYKEY

(

STUDENT_ID

,SEMESTER

)

ENABLE

)

CREATETABLEEMPLOYEE_DETAILS

(

EMPLOYEE_IDNUMBERNOTNULL

,FIRST_NAMEVARCHAR2(20BYTE)

,MIDDLE_NAMEVARCHAR2(20BYTE)

,LAST_NAMEVARCHAR2(20BYTE)

,DATE_OF_BIRTHDATE

,MOBILE_NUMBERVARCHAR2(15BYTE)

,DEPARTMENTVARCHAR2(20BYTE)

,DESIGNATIONVARCHAR2(20BYTE)

,HIRE_DATEDATE

,SEXVARCHAR2(1BYTE)

,ACTIVE_FLAGVARCHAR2(1BYTE)

,ADDRESSVARCHAR2(100BYTE)

,MANAGER_IDNUMBER

,CONSTRAINTEMPLOYEE_ID_PKPRIMARYKEY

(

EMPLOYEE_ID

)

ENABLE

)

CREATETABLEPARENT_DETAILS

(

FATHER_NAMEVARCHAR2(30BYTE)

,MOTHER_NAMEVARCHAR2(30BYTE)

,GUARDIAN_NAMEVARCHAR2(30BYTE)

,FATHER_MOBILEVARCHAR2(15BYTE)

,MOTHER_MOBILEVARCHAR2(15BYTE)

,GUARDIAN_MOBILEVARCHAR2(10BYTE)

,ADDRESSVARCHAR2(100BYTE)

,FATHER_QUALIFICATIONVARCHAR2(50BYTE)

,MOTHER_QUALIFICATIONVARCHAR2(50BYTE)

,ANNUAL_INCOMEVARCHAR2(10BYTE)

,STUDENT_IDVARCHAR2(16BYTE)NOTNULL

,CONSTRAINTPARENTDETAILSPKPRIMARYKEY

(

STUDENT_ID

)

ENABLE

)

CREATETABLESCHOLASTIC_RESULTS

(

STUDENT_IDVARCHAR2(16BYTE)NOTNULL

,SEMESTERVARCHAR2(1BYTE)NOTNULL

,ENGLISH_GRADEVARCHAR2(1BYTE)

,MATHS_GRADEVARCHAR2(1BYTE)

,SCIENCE_GRADEVARCHAR2(1BYTE)

,SOCIAL_GRADEVARCHAR2(1BYTE)

,LANG2_GRADEVARCHAR2(1BYTE)

,LANG3_GRADEVARCHAR2(1BYTE)

,COMPSC_GRADEVARCHAR2(1BYTE)

,ARTS_GRADEVARCHAR2(1BYTE)

,MUSIC_GRADEVARCHAR2(1BYTE)

,DANCE_GRADEVARCHAR2(1BYTE)

,PHYSICALEDU_GRADEVARCHAR2(1BYTE)

,VALUEEDU_GRADEVARCHAR2(1BYTE)

,SCHOOLPROJECT_GRADEVARCHAR2(1BYTE)

,ENGLISH_REMVARCHAR2(150BYTE)

,MATHS_REMVARCHAR2(150BYTE)

,SCIENCE_REMVARCHAR2(150BYTE)

,SOCIAL_REMVARCHAR2(150BYTE)

,LANG2_REMVARCHAR2(150BYTE)

,LANG3_REMVARCHAR2(150BYTE)

,COMPSC_REMVARCHAR2(150BYTE)

,ARTS_REMVARCHAR2(150BYTE)

,MUSIC_REMVARCHAR2(150BYTE),DANCE_REMVARCHAR2(150BYTE)

,PHYSICALEDU_REMVARCHAR2(150BYTE)

,VALUEEDU_REMVARCHAR2(150BYTE)

,SCHOOLPROJECT_REMVARCHAR2(150BYTE)

,CONSTRAINTSR_CPKPRIMARYKEY

(

STUDENT_ID

,SEMESTER

)

ENABLE

)

CREATETABLESTUDENT_ATTENDANCE

(

STUDENT_IDVARCHAR2(16BYTE)NOTNULL

,ATTENDANCENUMBER

,SEMESTERVARCHAR2(1BYTE)NOTNULL

,CONSTRAINTSA_CPKPRIMARYKEY

(

STUDENT_ID

,SEMESTER

)

ENABLE

)

CREATETABLESTUDENT_DETAILS

(

ACTIVE_FLAGVARCHAR2(1BYTE)NOTNULL

,FIRST_NAMEVARCHAR2(20BYTE)

,MIDDLE_NAMEVARCHAR2(20BYTE)

,LAST_NAMEVARCHAR2(20BYTE)

,GENDER_CODEVARCHAR2(1BYTE)

,BIRTH_DATEDATE

,BIRTH_CITY_NAMEVARCHAR2(20BYTE)

,BIRTH_STATE_CODEVARCHAR2(2BYTE)

,BIRTH_COUNTRY_CODEVARCHAR2(2BYTE)

,BLOOD_GROUPVARCHAR2(3BYTE)

,BUS_IDNUMBER

,STUDENT_IDVARCHAR2(16BYTE)NOTNULL

,GRADEVARCHAR2(4BYTE)

,SECTIONVARCHAR2(1BYTE)

,HEIGHTVARCHAR2(3BYTE)

,WEIGHTVARCHAR2(3BYTE)

,SIBLINGS_STUDENT_IDSVARCHAR2(100BYTE)

,CONSTRAINTSTUDENTIDPKPRIMARYKEY

(

STUDENT_ID

)

ENABLE

)

CREATETABLESTUDENT_FEES

(

STUDENT_IDVARCHAR2(16BYTE)NOTNULL

,JAN_ACADVARCHAR2(1BYTE)

,FEB_ACADVARCHAR2(1BYTE)

,MAR_ACADVARCHAR2(1BYTE)

,APR_ACADVARCHAR2(1BYTE)

,MAY_ACADVARCHAR2(1BYTE)

,JUN_ACADVARCHAR2(1BYTE)

,JUL_ACADVARCHAR2(1BYTE)

,AUG_ACADVARCHAR2(1BYTE)

,SEP_ACADVARCHAR2(1BYTE)

,OCT_ACADVARCHAR2(1BYTE)

,NOV_ACADVARCHAR2(1BYTE)

,DEC_ACADVARCHAR2(1BYTE)

,JAN_BUSVARCHAR2(1BYTE)

,FEB_BUSVARCHAR2(1BYTE)

,MAR_BUSVARCHAR2(1BYTE)

,APR_BUSVARCHAR2(1BYTE)

,MAY_BUSVARCHAR2(1BYTE)

,JUN_BUSVARCHAR2(1BYTE)

,JUL_BUSVARCHAR2(1BYTE)

,AUG_BUSVARCHAR2(1BYTE)

,SEP_BUSVARCHAR2(1BYTE)

,OCT_BUSVARCHAR2(1BYTE)

,NOV_BUSVARCHAR2(1BYTE)

,DEC_BUSVARCHAR2(1BYTE)

,REMARKSVARCHAR2(200BYTE)

,CONSTRAINTSF_PKPRIMARYKEY

(

STUDENT_ID

)

ENABLE

)

CREATETABLETRANSPORTATION_DETAILS

(

BUS_IDNUMBERNOTNULL

,TRANSPORTATION_TYPEVARCHAR2(12BYTE)

,DRIVER_EMPLOYEE_IDNUMBER

,BUS_NUMBERVARCHAR2(12BYTE)

,HELPER_EMPLOYEE_IDNUMBER

,CONSTRAINTTD_PKPRIMARYKEY

(

BUS_ID

)

ENABLE

)

ALTERTABLECLASS_TEACHER_MAPPING

ADDCONSTRAINTCTM_FKFOREIGNKEY

(

EMPLOYEE_ID

)

REFERENCESEMPLOYEE_DETAILS

(

EMPLOYEE_ID

)

ENABLE;

ALTERTABLECOSCHOLASTIC_RESULTS

ADDCONSTRAINTCSR_FKFOREIGNKEY

(

STUDENT_ID

)

REFERENCESSTUDENT_DETAILS

(

STUDENT_ID

)

ENABLE;

ALTERTABLEPARENT_DETAILS

ADDCONSTRAINTSTUDENTIDFKFOREIGNKEY

(

STUDENT_ID

)

REFERENCESSTUDENT_DETAILS

(

STUDENT_ID

)

ENABLE;

ALTERTABLESCHOLASTIC_RESULTS

ADDCONSTRAINTSR_FKFOREIGNKEY

(

STUDENT_ID

)

REFERENCESSTUDENT_DETAILS

(

STUDENT_ID

)

ENABLE;

ALTERTABLESTUDENT_ATTENDANCE

ADDCONSTRAINTSA_FKFOREIGNKEY

(

STUDENT_ID

)

REFERENCESSTUDENT_DETAILS

(

STUDENT_ID

)

ENABLE;

ALTERTABLESTUDENT_DETAILS

ADDCONSTRAINTSD_FKFOREIGNKEY

(

BUS_ID

)

REFERENCESTRANSPORTATION_DETAILS

(

BUS_ID

)

ENABLE;

ALTERTABLESTUDENT_FEES

ADDCONSTRAINTSF_FKFOREIGNKEY

(

STUDENT_ID

)

REFERENCESSTUDENT_DETAILS

(

STUDENT_ID

)

ENABLE;

ALTERTABLETRANSPORTATION_DETAILS

ADDCONSTRAINTTD_DFKFOREIGNKEY

(

DRIVER_EMPLOYEE_ID)

REFERENCESEMPLOYEE_DETAILS

(

EMPLOYEE_ID

)

ENABLE;

ALTERTABLETRANSPORTATION_DETAILS

ADDCONSTRAINTTD_HFKFOREIGNKEY

(

HELPER_EMPLOYEE_ID

)

REFERENCESEMPLOYEE_DETAILS

(

EMPLOYEE_ID

)

ENABLE;

AbouttheAuthor

TheauthorMirzaYousufAhmedBaigholdsaMaster’sdegreeinComputerScienceEngineeringfromJawaharlalNehruTechnologicalUniversity,Hyderabad,India.Andabachelor’sdegreeinelectronicsandcommunicationengineeringfromGulbargaUniversity,India.Hehasdeliveredmorethan20corporatetrainingsoncoreJavatoITMNCs.

TheauthorhasworkedatvariousseniortechnicalrolesforOracleIndia,SunMicrosystemsandBEASystemsR&D.HehasworkedasTechnicalConsultantforSunMicrosystemsandPrincipalEngineerforOracleIndia.HehashandsonexperienceofmorethanoneandhalfdecadeonJava,JEEandOracleFusionMiddlewareProductsincludingOracleSOASuite,OracleAIA,OracleWebCenterandOracleADF.HehasbeenArchitecting,Designing,CodingandSupportingsoftwaresolutionsofvariouscomplexityandsizesduringhisentirecareer.

Theauthorhasbeenadirecttechnologicalliaisonforfortune500clientsinUSAandIndia.HehasworkedinUAEatclientsiteasanArchitectforimplementingweb2.0andintegrationsolutionsforAbuDhabigovernmentsectorclients.

TheauthorisSunCertifiedJavaCAPSintegratorandOraclePartnerNetwork(OPN)CertifiedSpecialistforOracleWebCenter11g.Heisalsoamongthetop10rankholdersinIndiaforICFAI’sGKnationallevelcompetition.HehasbeenrecognizedbyComputerSciencesCorporation(CSC)withanoutstandingperformeraward.Altriagroup,USAhashonoredhimasFieldCombatSpecialist1stclassforhiscontributionsasawebdeveloper.

top related